You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.
Return trueif you can reach the last index, orfalseotherwise.
OR
Write a function to determine whether a person can reach the other end of the array if he starts at index 0 and if they cannot hop more than the value contained at that index.
Input: nums =[2,3,1,1,4]Output: trueExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
1
2
3
Input: nums =[3,2,1,0,4]Output: falseExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is0, which makes it impossible to reach the last index.
We can start from index 0, and keep on jumping, till we reach out goal or point of failure.
---
title: Recursion tree for nums=[3,2,1,0,4]
---
graph TD;
A(0) ---|1| B(1)
A ---|2| C(2)
A ---|3| D(3):::deadend
B ---|1| E(2)
B ---|2| F(3):::deadend
E ---|1| G(3):::deadend
C ---|1| H(3):::deadend
classDef deadend fill:#ffcccc,color:#900,font-weight:bold;
classSolution {
publicbooleancanJump(int[] nums) {
// Start recursion from the first indexreturn dfs(0, nums);
}
// Recursive helper method to explore jumpsprivatebooleandfs(int pos, int[] nums) {
// Base case: If we reach or pass the last index, return trueif (pos >= nums.length- 1) {
returntrue;
}
// Explore all jumps from the current positionfor (int nextPos = 1; nextPos <= nums[pos]; nextPos++) {
if (dfs(pos + nextPos, nums)) {
returntrue;
}
}
// If no valid path is found, return falsereturnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defcanJump(self, nums: List[int]) -> bool:
defdfs(position: int) -> bool:
# Base case: If we reach the last index, return Trueif position >= len(nums) -1:
returnTrue# Explore all jumps from the current positionfor next_pos in range(1, nums[position] +1):
if dfs(position + next_pos):
returnTrue# If no valid path is found, return FalsereturnFalse# Start recursion from the first indexreturn dfs(0)
We can look at the decision tree above, we see repetitive problems. We can use cache dp[] as boolean array, to see if we already solved that problem. If the step is true, then previous step can also be true, if it part of the array.
classSolution {
publicbooleancanJump(int[] nums) {
// Create a cache for memoization Map<Integer, Boolean> cache =new HashMap<>();
// Call the helper method starting from the first indexreturn dfs(0, nums, cache);
}
// Helper method for recursive exploration with cachingprivatebooleandfs(int pos, int[] nums, Map<Integer, Boolean> cache) {
// Base case: If we reach or exceed the last index, return trueif (pos >= nums.length- 1) {
returntrue;
}
// Check if the current position is already in the cacheif (cache.containsKey(pos)) {
return cache.get(pos);
}
// Explore all possible jumps from the current positionint maxJump = nums[pos];
for (int nextPos = 1; nextPos <= maxJump; nextPos++) {
if (dfs(pos + nextPos, nums, cache)) {
cache.put(pos, true); // Cache the resultreturntrue;
}
}
// If no valid path can be found, cache the result and return false cache.put(pos, false);
returnfalse;
}
}
classSolution:
defcanJump(self, nums: List[int]) -> bool:
cache = {}
defdfs(position: int) -> bool:
# Base case: If we reach or exceed the last indexif position >= len(nums) -1:
returnTrue# Check cacheif position in cache:
return cache[position]
# Explore jumps from this position max_jump = nums[position]
for next_pos in range(1, max_jump +1):
if dfs(position + next_pos):
cache[position] =True# Cache resultreturnTrue# Cache negative result if no path works cache[position] =FalsereturnFalse# Start recursion from index 0return dfs(0)
We can solve this problem by starting from the end of the array and moving to the left. Suppose m is the last index. If we can reach from m-1 to m, we can shift the goal post from m to m-1 and continue. Essentially, if we find that the current position can reach the goal (i.e., the last index), we move the goal to this current position and repeat the process until we either reach the start of the array or determine that it’s impossible.
classSolution {
publicbooleancanJump(int[] nums) {
int goal = nums.length- 1; // Start with the goal at the last index// Iterate from right to leftfor (int i = nums.length- 2; i >= 0; i--) {
// Check if the current index can reach the current goalif (i + nums[i]>= goal) {
goal = i; // Shift the goal backward to this index }
}
// At the end, check if the goal has shifted all the way back to index 0return goal == 0;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defcanJump(self, nums: List[int]) -> bool:
goal = len(nums) -1# Start with the goal at the last index# Iterate from right to leftfor i in range(len(nums) -2, -1, -1):
# Check if the current index can reach the current goalif i + nums[i] >= goal:
goal = i # Shift the goal backward to this index# At the end, check if the goal has shifted all the way back to index 0return goal ==0
publicclassSolution {
publicbooleancanJump(int[] nums) {
int maxReach = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
if (i > maxReach) {
returnfalse;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= n - 1) {
returntrue;
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcanJump(self, nums: List[int]) -> bool:
max_reach: int =0 n: int = len(nums)
for i in range(n):
if i > max_reach:
returnFalse max_reach = max(max_reach, i + nums[i])
if max_reach >= n -1:
returnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::cmp;
pubfncan_jump(nums: Vec<i32>) -> bool {
if nums.len() <=1 { returntrue; }
let n = nums.len();
letmut coverage =0;
for i in0..n {
if coverage < i {
returnfalse;
}
coverage = cmp::max(coverage, i + nums[i] asusize);
if (coverage >= n) {
returntrue;
}
}
returntrue;
}
Focus on the current position (curr) and keep updating the furthest position (right) that can be reached. This approach ensures that you are always aware of the maximum index you can jump to, and you can confidently determine if the end of the array is reachable.
As we move through the array, we update right each time we find that we can reach further from the current index. If right becomes greater than or equal to the length of the array, it means we can reach the end, so we return true. If we exhaust the while loop without reaching the end, we return false.
publicclassSolution {
publicbooleancanJump(int[] nums) {
int curr = 0;
int right = 1;
while (curr <= right) {
int val = nums[curr];
if (curr + val > right) {
right = curr + val;
}
if (right >= nums.length- 1) {
returntrue;
}
curr++;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcanJump(self, nums: List[int]) -> bool:
curr: int =0 right: int =0while curr <= right:
val = nums[curr]
right = max(right, curr + val)
if right >= len(nums) -1:
returnTrue curr +=1returnFalse