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

  1. Attach the method to Array.prototype so every array instance inherits it.
  2. Use this.length to test for emptiness and return this[this.length - 1] otherwise.
  3. Do not use an arrow function: it does not bind this, so it would capture the enclosing scope instead of the array.
  4. 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: this would not refer to the array instance.
  • Using this[-1]: JavaScript arrays do not support negative indices.
  • Returning undefined for an empty array: the problem requires -1.
  • Using this.pop(): that mutates the array.