LeetCode 2619: Array Prototype Last Solution
Master LeetCode problem 2619 (Array Prototype Last), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2619. Array Prototype Last
Problem Explanation
Explanation
To solve this problem, we need to enhance the array prototype in such a way that we can call array.last() on any array and it will return the last element of the array. If the array is empty, it should return -1. The idea is to add a new function last() to the Array.prototype in JavaScript which will return the last element of the array if it exists, otherwise return -1.
- Algorithmic Idea:
- Check if the array is empty, return -1 if true.
- Otherwise, return the last element of the array.
- Time Complexity: O(1) - Constant time complexity as we are directly accessing the last element of the array.
- Space Complexity: O(1) - Constant space complexity as we are not using any extra space.
Solution Code
import java.util.ArrayList;
public class EnhancedArrayPrototype {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.add(null);
nums.add(3);
System.out.println(nums.last());
}
}
class EnhancedArrayPrototype {
public static int last() {
if (this.isEmpty()) {
return -1;
}
return this.get(this.size() - 1);
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2619 (Array Prototype Last)?
This page provides optimized solutions for LeetCode problem 2619 (Array Prototype Last) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2619 (Array Prototype Last)?
The time complexity for LeetCode 2619 (Array Prototype Last) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2619 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2619 in Java, C++, or Python.