Jump Game
Medium · Greedy
Jump to codeEach nonnegative array value is the maximum jump length allowed from that index. Starting at index 0, determine whether you can reach the final index of a nonempty array.
Examples
Example 1
nums = [2,3,1,1,4]
Output: true
Example 2
nums = [3,2,1,0,4]
Output: false
Constraints
- 1 <= nums.length <= 1000
- 0 <= nums[i] <= 1000
Need a hint?
Track the farthest reachable index rather than committing to a particular jump.
Asked in real interviews
Candidates reported versions of Jump Game from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Scan while the current index is within the reachable range. Extend farthest with max(farthest, index + jumpLength). Return true once it reaches the last index. If the next index lies beyond farthest, an unavoidable gap makes the answer false.
Complexity
O(n) time and O(1) space.
Python reference solution
def canJump(nums):
farthest = 0
for i, distance in enumerate(nums):
if i > farthest:
return False
farthest = max(farthest, i + distance)
if farthest >= len(nums) - 1:
return True
return False
JavaScript solution
function canJump(nums) {
let farthest = 0;
for (let i = 0; i < nums.length; i++) {
if (i > farthest) return false;
farthest = Math.max(farthest, i + nums[i]);
if (farthest >= nums.length - 1) return true;
}
return false;
}
Java solution
import java.util.*;
class Solution {
public boolean canJump(int[] nums) {
int farthest = 0;
for (int i = 0; i < nums.length; i++) {
if (i > farthest) return false;
farthest = Math.max(farthest, i + nums[i]);
if (farthest >= nums.length - 1) return true;
}
return false;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool canJump(vector<int> &nums) {
int farthest = 0;
for (int i = 0; i < (int)nums.size(); i++) {
if (i > farthest) return false;
farthest = max(farthest, i + nums[i]);
if (farthest >= (int)nums.size() - 1) return true;
}
return false;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
2,
3,
1,
1,
4
]
]true
[
[
3,
2,
1,
0,
4
]
]false
[
[
0
]
]true
[
[
2,
0,
0
]
]true
[
[
1,
0,
1,
0
]
]false
Drafts are saved per language in this browser when storage is available.