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 <= 1000This approach involves extending the Array prototype such that a method last() can be directly called on any array instance. If the array is empty, it should return -1; otherwise, it should return the last element of the array.
In JavaScript, we can directly augment the Array.prototype to add a new method last(). This method checks if the array is empty and returns -1 if true, otherwise it returns the last element using this[this.length - 1].
Time complexity is O(1) as accessing an array element by index is constant time. Space complexity is O(1) as no extra space is used.
This approach involves creating a separate utility function that operates on arrays to return the last element or -1 if the array is empty. This is useful where extending native objects is not recommended or possible.
In C, we write a utility function lastElement that takes an array and its length as arguments. It returns -1 if the length is zero, otherwise, it returns the last element using arr[length - 1]. This approach avoids trying to augment the C array prototype, which is not possible in C.
C++
Java
Python
C#
Time complexity is O(1) since accessing the last element by index is constant time. Space complexity is O(1) as no additional space is needed.
| Approach | Complexity |
|---|---|
| Prototype Method Enhancement | Time complexity is O(1) as accessing an array element by index is constant time. Space complexity is O(1) as no extra space is used. |
| Utility Function Approach | Time complexity is O(1) since accessing the last element by index is constant time. Space complexity is O(1) as no additional space is needed. |
Array Prototype Last - Leetcode 2619 - JavaScript 30-Day Challenge • NeetCodeIO • 4,426 views views
Watch 9 more video solutions →Practice Array Prototype Last with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor