#2619

Array Prototype Last

Easy
Array
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution is essentially the same as the brute force approach since accessing the last element of an array is inherently efficient. We can directly implement the method without any additional checks.

⚙️

Algorithm

2 steps
  1. 1Step 1: Define a method on Array.prototype called last.
  2. 2Step 2: Return the last element if the array has elements, otherwise return -1.
solution.py4 lines
1def last(self):
2    return self[-1] if len(self) > 0 else -1
3
4setattr(list, 'last', last)

Complexity note: The time complexity remains O(1) as we are directly accessing the last element. The space complexity is O(1) since no extra space is used.

  • 1Understanding how to extend built-in objects like arrays is crucial in JavaScript.
  • 2Directly accessing array elements is efficient and should be leveraged.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.