Problem Description
This problem requires extending the functionality of all arrays by adding a new method, last(), which returns the last element of the array. If the array is empty, the method should return -1.
Key Insights
- Extend the built-in Array type with a new method.
- Check if the array is empty by verifying its length.
- Return the last element by accessing the element at index length - 1.
- Ensure the solution works with arrays (including those produced by JSON.parse).
Space and Time Complexity
Time Complexity: O(1) per call, as accessing an element by index is constant time. Space Complexity: O(1) additional space, as no extra data structures are used.
Solution
We solve the problem by modifying the Array prototype to include a new method last(). When the method is called, it checks if the array's length is zero; if it is, it returns -1. Otherwise, it returns the element at index length - 1. This approach leverages a simple conditional check and direct index access, ensuring both clarity and efficiency.