NeetCode #966LC-2619EasyJavaScript
← Back to All Problems#966 · #2619 · Array Prototype Last(数组原型上的最后一个元素)
📌 Problem Statement & Constraints
Implement
Array.prototype.last(): return the last element of the array, or -1 if the array is empty.💡 Core Algorithmic Approaches
- Attach the method to
Array.prototypeso every array instance inherits it. - Use
this.lengthto test for emptiness and returnthis[this.length - 1]otherwise. - Do not use an arrow function: it does not bind
this, so it would capture the enclosing scope instead of the array. - An empty array returns -1, as the problem specifies.
💻 Benchmark Python3 Implementation
Array.prototype.last = function() {
// A regular function is required: an arrow function does not bind this
return this.length > 0 ? this[this.length - 1] : -1;
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1): constant time.
💾 Space Complexity
O(1): constant space.
⚠️ Interview Pitfalls & Follow-ups
- Defining the method as an arrow function:
thiswould not refer to the array instance. - Using
this[-1]: JavaScript arrays do not support negative indices. - Returning
undefinedfor an empty array: the problem requires -1. - Using
this.pop(): that mutates the array.