We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Prototype Last

Difficulty: Easy


Problem Description

Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1. You may assume the array is the output of JSON.parse.


Key Insights

  • The problem requires modifying the Array prototype to add a new method.
  • The new method should handle edge cases where the array is empty.
  • Returning the last element of an array can be achieved using the length property.

Space and Time Complexity

Time Complexity: O(1) - Accessing the last element of an array is a constant time operation. Space Complexity: O(1) - No additional space is used that scales with input size.


Solution

To solve this problem, we will enhance the Array prototype by adding a method named last. This method will check if the array has any elements. If it does, it will return the last element using the array's length property. If the array is empty, it will return -1. This approach utilizes the inherent properties of the array data structure in JavaScript.


Code Solutions

Array.prototype.last = function() {
    // Check if the array is empty
    if (this.length === 0) {
        return -1; // Return -1 for an empty array
    }
    // Return the last element using the length property
    return this[this.length - 1];
};
← Back to All Questions