Array Prototype Last - Problem
Enhance JavaScript's built-in Array prototype by implementing a custom last() method that can be called on any array instance. This method should return the last element of the array, or -1 if the array is empty.
Your implementation should work seamlessly with all arrays, including those created from JSON.parse(). This is a fundamental operation similar to peek operations in stack data structures.
Examples:
[1, 2, 3].last()→3["hello", "world"].last()→"world"[].last()→-1
This problem teaches you about JavaScript's prototype system and how to extend built-in objects safely.
Input & Output
example_1.js — Basic Array
$
Input:
[1, 2, 3, 4, 5].last()
›
Output:
5
💡 Note:
The last element in the array [1, 2, 3, 4, 5] is 5, so the method returns 5.
example_2.js — String Array
$
Input:
["apple", "banana", "cherry"].last()
›
Output:
"cherry"
💡 Note:
The last element in the string array is "cherry", which is returned as-is.
example_3.js — Empty Array
$
Input:
[].last()
›
Output:
-1
💡 Note:
Since the array is empty (length = 0), the method returns -1 as specified in the problem requirements.
Visualization
Tap to expand
Understanding the Visualization
1
Check Array Length
First verify the array isn't empty to avoid errors
2
Calculate Last Index
For arrays, last index = length - 1 due to zero-based indexing
3
Direct Access
Use bracket notation to instantly retrieve the element
Key Takeaway
🎯 Key Insight: Arrays provide constant-time access by index. The last element is always at position `length - 1`, making this operation incredibly efficient.
Time & Space Complexity
Time Complexity
O(1)
Direct array access by index is a constant-time operation
✓ Linear Growth
Space Complexity
O(1)
No additional data structures needed, only the method call overhead
✓ Linear Space
Constraints
- The array can contain any valid JSON values (numbers, strings, booleans, null, objects, arrays)
- Array length can be 0 ≤ length ≤ 1000
- Must return exactly -1 for empty arrays
- Must extend Array.prototype in JavaScript
- Must work with arrays created from JSON.parse()
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code