Talentd
FleetCode
Make and follow sheets.Sign in

Array Prototype Last solution and explanation

Easy3 min read74.0% acceptanceUpdated 9 Apr 2026
Array Prototype Last - Leetcode 2619 - JavaScript 30-Day ChallengeNeetCodeIO · 6:17 · 5K viewsWatch on YouTube
9 more videos on this problem
  1. Array Prototype Last - Leetcode 2619 - JavaScript 30-Day ChallengeNeetCodeIO · 6:17 · 5K views
  2. Array Prototype Last | Leetcode 2619 | JSON | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 5:27 · 1K views
  3. 2619. Array Prototype Last - Day 23/30 Leetcode Javascript ChallengeProgramming Live with Larry · 1:26 · 358 views
  4. #day22 | 2619. Array Prototype Last | 30 Days of JavaScript | Leetcode-2619 | JSON | this keywordCoding with Ankita · 5:09 · 280 views
  5. Array Prototype Last Leetcode Problem SolutionSaurabh Native · 4:57 · 137 views
  6. Array Prototype Last (Leetcode 2619) in TeluguCoding Interview Preparation · 2:04 · 122 views
  7. Day 23. LeetCode 2619. Array Prototype Last. Daily JS challengeКанал про вирішення ЛітКод Українською · 3:12 · 118 views
  8. Solving LeetCode Challenge Day 23: Array Prototype Last - 2619 | Enhance Your Arrays in JavaScriptvanAmsen · 3:30 · 114 views
  9. LeetCode 2619: Add .last() Method to ArraysScott Hacks Code · 3:00 · 94 views
  10. Array Prototype Last - LeetCode 2619 - JavaScript - JS 30 Day Challenge Day 23Alpha-Code · 7:20 · 93 views

The problem

Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.

You may assume the array is the output of JSON.parse.

Example 1:

Input: nums = [null, {}, 3]
Output: 3
Explanation: Calling nums.last() should return the last element: 3.

Example 2:

Input: nums = []
Output: -1
Explanation: Because there are no elements, return -1.

Constraints:

  • arr is a valid JSON array
  • 0 <= arr.length <= 1000

Approach overview

Problem Overview: You need to return the last element of an array. If the array is empty, return -1. In JavaScript, the task specifically asks you to extend Array.prototype with a last() method that behaves this way.

Approach 1: Prototype Method Enhancement (O(1) time, O(1) space)

This approach directly extends Array.prototype by adding a last() method. Inside the method, check the array length. If this.length === 0, return -1. Otherwise, access the last element using index this.length - 1. The key insight is that JavaScript arrays allow constant-time index access, so retrieving the final element requires no iteration. This solution follows the exact requirement of modifying the prototype and demonstrates understanding of JavaScript object behavior.

Approach 2: Utility Function with Direct Index Access (O(1) time, O(1) space)

In languages like C, C++, Java, Python, or C#, prototype modification is not relevant. Instead, implement a small helper function that accepts an array and returns its last element. Check if the array size is zero; if so, return -1. Otherwise, return the value at index n - 1. This relies on constant-time random access provided by arrays. The algorithm performs only a length check and a single index operation, keeping both time and space complexity constant.

Both solutions rely on the same core observation: the last element of an array is always accessible using the index length - 1. No traversal or additional data structures are required.

Recommended for interviews: The direct index access approach is what interviewers expect. It shows you understand array indexing and boundary conditions. When solving the JavaScript-specific version, implementing the Array.prototype.last method demonstrates familiarity with prototypes and built-in object extension. Both solutions run in O(1) time and O(1) space, which is optimal for this problem.

Approach 1: Prototype Method Enhancement

This approach involves extending the Array prototype such that a method last() can be directly called on any array instance. If the array is empty, it should return -1; otherwise, it should return the last element of the array.

Array.prototype.last = function() {
    return this.length === 0 ? -1 : this[this.length - 1];
};

In JavaScript, we can directly augment the Array.prototype to add a new method last(). This method checks if the array is empty and returns -1 if true, otherwise it returns the last element using this[this.length - 1].

Complexity

Time complexity is O(1) as accessing an array element by index is constant time. Space complexity is O(1) as no extra space is used.

Try this approach in the editor

Approach 2: Utility Function Approach

This approach involves creating a separate utility function that operates on arrays to return the last element or -1 if the array is empty. This is useful where extending native objects is not recommended or possible.

def last_element(lst):
    return -1 if not lst else lst[-1]

nums = [0, 2, 9]
print(last_element(nums))
import java.util.List;

public class LastElementUtil {
    public static <T> T getLastElement(List<T> list) {
        return list.isEmpty() ? -1 : list.get(list.size() - 1);
    }

    public static void main(String[] args) {
        List<Integer> nums = List.of(0, 2, 9);
        System.out.println(getLastElement(nums));
    }
}
#include <iostream>
#include <vector>

int lastElement(const std::vector<int>& arr) {
    return arr.empty() ? -1 : arr.back();
}

int main() {
    std::vector<int> nums = {0, 2, 9};
    std::cout << lastElement(nums);
    return 0;
}
#include <stdbool.h>
#include <stdio.h>

int lastElement(int arr[], int length) {
    return length == 0 ? -1 : arr[length - 1];
}

int main() {
    int nums[] = {0, 2, 9};
    int length = sizeof(nums)/sizeof(nums[0]);
    printf("%d", lastElement(nums, length));
    return 0;
}
using System;
using System.Collections.Generic;

public class Program
{
    public static int GetLastElement(List<int> list)
    {
        return list.Count == 0 ? -1 : list[list.Count - 1];
    }

    public static void Main()
    {
        List<int> nums = new List<int> { 0, 2, 9 };
        Console.WriteLine(GetLastElement(nums));
    }
}

In Python, the function last_element returns -1 if the list is empty; otherwise, it utilizes Python's list indexing to return lst[-1], which retrieves the last element.

Complexity

Time complexity is O(1) as indexing is constant time. Space complexity is O(1) as it doesn't require additional storage.

Try this approach in the editor

Approach 3: Default Approach

declare global {
    interface Array<T> {
        last(): T | -1;
    }
}

Array.prototype.last = function () {
    return this.length ? this.at(-1) : -1;
};

/**
 * const arr = [1, 2, 3];
 * arr.last(); // 3
 */

export {};
Try this approach in the editor

Complexity comparison

ApproachComplexity
Prototype Method Enhancement

Time complexity is O(1) as accessing an array element by index is constant time. Space complexity is O(1) as no extra space is used.

Utility Function Approach

Time complexity is O(1) as indexing is constant time. Space complexity is O(1) as it doesn't require additional storage.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Prototype Method EnhancementO(1)O(1)JavaScript-specific problems requiring extension of Array.prototype
Utility Function with Direct Index AccessO(1)O(1)General solution for languages like Python, Java, C++, or C#

Frequently asked questions

Is Array Prototype Last easy or hard?

Array Prototype Last is classified as an Easy problem. The main concept is handling the empty array edge case and retrieving the final element using constant-time array indexing.

Array Prototype Last Python/Java solution

In Python or Java, implement a helper function that returns -1 if the array or list is empty; otherwise return arr[len(arr) - 1] in Python or arr[n - 1] in Java. Both implementations run in O(1) time and O(1) space.

How to solve Array Prototype Last in O(1)?

Use direct index access. If the array is empty, return -1. Otherwise return the element at index n - 1 where n is the array length. This avoids loops and keeps the solution constant time.

What is the best approach for Array Prototype Last?

The best approach is direct index access. Check if the array length is zero and return -1; otherwise return the element at index length - 1. This works in O(1) time and O(1) space since array indexing is constant time.

Is Array Prototype Last asked at Google/Amazon/Meta?

Array Prototype Last is a basic array manipulation problem commonly used in coding platforms to test understanding of language features and edge cases. While simpler than typical FAANG interview questions, similar array boundary problems appear in early screening rounds.

What data structure is used in Array Prototype Last?

The problem uses a standard array data structure. The solution relies on constant-time random access provided by arrays to retrieve the last element using index length - 1.

What is the time complexity of Array Prototype Last?

The time complexity is O(1). The algorithm performs only a length check and a single array index lookup, both constant-time operations. No iteration or additional processing is required.

Comments

Now write it yourselfClose this page and solve Array Prototype Last in the editor, without looking.
Practise Array Prototype Last