Watch 10 video solutions for Array Prototype Last, a easy level problem. This walkthrough by NeetCodeIO has 5,308 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Example 1:
Input: nums = [null, {}, 3]
Output: 3
Explanation: Calling nums.last() should return the last element: 3.
Example 2:
Input: nums = [] Output: -1 Explanation: Because there are no elements, return -1.
Constraints:
arr is a valid JSON array0 <= arr.length <= 1000Problem Overview: You need to return the last element of an array. If the array is empty, return -1. In JavaScript, the task specifically asks you to extend Array.prototype with a last() method that behaves this way.
Approach 1: Prototype Method Enhancement (O(1) time, O(1) space)
This approach directly extends Array.prototype by adding a last() method. Inside the method, check the array length. If this.length === 0, return -1. Otherwise, access the last element using index this.length - 1. The key insight is that JavaScript arrays allow constant-time index access, so retrieving the final element requires no iteration. This solution follows the exact requirement of modifying the prototype and demonstrates understanding of JavaScript object behavior.
Approach 2: Utility Function with Direct Index Access (O(1) time, O(1) space)
In languages like C, C++, Java, Python, or C#, prototype modification is not relevant. Instead, implement a small helper function that accepts an array and returns its last element. Check if the array size is zero; if so, return -1. Otherwise, return the value at index n - 1. This relies on constant-time random access provided by arrays. The algorithm performs only a length check and a single index operation, keeping both time and space complexity constant.
Both solutions rely on the same core observation: the last element of an array is always accessible using the index length - 1. No traversal or additional data structures are required.
Recommended for interviews: The direct index access approach is what interviewers expect. It shows you understand array indexing and boundary conditions. When solving the JavaScript-specific version, implementing the Array.prototype.last method demonstrates familiarity with prototypes and built-in object extension. Both solutions run in O(1) time and O(1) space, which is optimal for this problem.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Prototype Method Enhancement | O(1) | O(1) | JavaScript-specific problems requiring extension of Array.prototype |
| Utility Function with Direct Index Access | O(1) | O(1) | General solution for languages like Python, Java, C++, or C# |