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.