Difficulty: Easy | Acceptance: 74.70% | Paid: No Topics: N/A
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.
- Examples
- Constraints
- Direct Index Access
- Using Array Methods
Examples
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
0 <= arr.length <= 1000
Direct Index Access
Intuition Access the last element directly using the array’s length property to calculate the index, or return -1 if the array is empty.
Steps
- Check if the array length is 0, return -1 if true
- Return the element at index (length - 1)
python
class Solution:
def last(self, arr):
if len(arr) == 0:
return -1
return arr[-1]Complexity
- Time: O(1)
- Space: O(1)
- Notes: Most efficient approach with constant time and space complexity.
Using Array Methods
Intuition Leverage built-in array methods like pop() or slice() to extract the last element, handling the empty case separately.
Steps
- Check if the array is empty, return -1 if true
- Use pop() to remove and return the last element, or slice() to get a copy of the last element
python
class Solution:
def last(self, arr):
if not arr:
return -1
return arr.pop()Complexity
- Time: O(1)
- Space: O(1) for pop(), O(1) for slice(-1) as it creates a single-element array
- Notes: pop() modifies the original array, while slice() creates a copy. Direct index access is preferred for efficiency.