22- Jump to last index
Description
Given a non-empty array of non-negative integers arr, where each element represents the maximum jump that we can perform from that index, create a boolean function that checks if we can reach the last index starting from the first one.
Example 1:
- Input: arr = [3, 0, 2, 0, 2, 1, 4, 3]
- Output: true
- Explanation: we can for example jump from arr[0] to arr[2], then from arr[2] to arr[4], then from arr[4] to arr[6], then from arr[6] to arr[7] (the last index)
Example 2:
- Input: arr = [5, 3, 2, 0, 1, 0, 4]
- Output: false
- Explanation: we have no way to reach the last index
Try some input:
Try to solve:
Select a language:
Solution:
Code:
Select a language:
Python code:
By using recursion:
In case the code doesn't appear: click here
Time complexity: O(2^n)
Space complexity: O(n)
By using dynamic programming:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(n)
By keeping track of the max index that we can reach:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
Java code:
By using recursion:
In case the code doesn't appear: click here
Time complexity: O(2^n)
Space complexity: O(n)
By using dynamic programming:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(n)
By keeping track of the max index that we can reach:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
C++ code:
By using recursion:
In case the code doesn't appear: click here
Time complexity: O(2^n)
Space complexity: O(n)
By using dynamic programming:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(n)
By keeping track of the max index that we can reach:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
JavaScript code:
By using recursion:
In case the code doesn't appear: click here
Time complexity: O(2^n)
Space complexity: O(n)
By using dynamic programming:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(n)
By keeping track of the max index that we can reach:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
Frequently asked questions:
No questions yet.
You can ask a question in comment section below.
0 comments