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
Array.prototype.last() - Direct Access MethodArray: ["apple", "banana", "cherry", "date", "elderberry"]"apple""banana""cherry""date""elderberry"Index: 0Index: 1Index: 2Index: 3Index: 4this[this.length - 1]this[5 - 1] = this[4]Implementation:Array.prototype.last = function() {return this.length === 0 ? -1 : this[this.length - 1];};✓ O(1) Time✓ O(1) Space✓ No Loops
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

n
2n
Linear Growth
Space Complexity
O(1)

No additional data structures needed, only the method call overhead

n
2n
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()
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
42.0K Views
Medium Frequency
~8 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen