We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Prototype Last

Number: 2734

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Adobe, Apple, Meta


Problem Description

This problem requires extending the functionality of all arrays by adding a new method, last(), which returns the last element of the array. If the array is empty, the method should return -1.


Key Insights

  • Extend the built-in Array type with a new method.
  • Check if the array is empty by verifying its length.
  • Return the last element by accessing the element at index length - 1.
  • Ensure the solution works with arrays (including those produced by JSON.parse).

Space and Time Complexity

Time Complexity: O(1) per call, as accessing an element by index is constant time. Space Complexity: O(1) additional space, as no extra data structures are used.


Solution

We solve the problem by modifying the Array prototype to include a new method last(). When the method is called, it checks if the array's length is zero; if it is, it returns -1. Otherwise, it returns the element at index length - 1. This approach leverages a simple conditional check and direct index access, ensuring both clarity and efficiency.


Code Solutions

# Python solution using monkey patching of the built-in list class.
# We define a function that is then added as a method to list.

def last(self):
    # If the list is empty, return -1; otherwise, return the last element.
    return -1 if len(self) == 0 else self[-1]

# Bind the function as a method of the list class.
setattr(list, "last", last)

# Example usage:
nums = [None, {}, 3]
print(nums.last())  # Output: 3

nums_empty = []
print(nums_empty.last())  # Output: -1
← Back to All Questions