Jump Game
Medium
Topics
Given an array nums where each element is your maximum jump length from that position, return true if you can reach the last index.
Example 1
start and goal
Each cell is the maximum jump from that position, not a fixed one, so a position is reachable whenever some earlier jump clears it. That frontier never falls behind the current index here, so the end is reachable and the answer is
true.Cells are the array values; the small numbers underneath are indices.
Input: nums = [2,3,1,1,4] Output: true
Example 2
cannot be reached
Here the frontier stalls before index 4, which nothing can clear, so the answer is
false.Input: nums = [3,2,1,0,4] Output: false
Constraints
- 1 <= nums.length <= 10^4
- 0 <= nums[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Instead of trying jumps, track the farthest index reachable so far. As long as you never stand on an index beyond that reach, you can keep going; the moment an index exceeds the reach, you are stuck.
Approach
- Keep
reach = 0. - Scan indices; if
i > reach, return False. - Otherwise extend
reach = max(reach, i + nums[i]). - Finishing the scan means the end is reachable.
Walkthrough
nums = [3, 2, 1, 0, 4]
i=0 reach=3
i=1 reach=3
i=2 reach=3
i=3 reach=3
i=4 4>reach -> FalseComplexity
- Time — O(n): single greedy pass.
- Space — O(1): one variable.
Common Pitfalls
- Keep the
i > reachcheck. Without it the loop keeps updatingreachfrom indices it can never actually stand on, and every input returns true -- including[3,2,1,0,4], which is genuinely unreachable. reachis a maximum, not a running total. Adding jump lengths together assumes you take every jump at full length, which is not what the problem allows.
Full Solution — all languages
class Solution:
def canJump(self, nums):
reach = 0
for i, x in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + x)
return Trueimport java.util.*;
class Solution {
public boolean canJump(int[] nums) {
int reach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > reach) return false;
reach = Math.max(reach, i + nums[i]);
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool canJump(vector<int>& nums) {
int reach = 0;
for (int i = 0; i < (int)nums.size(); i++) {
if (i > reach) return false;
reach = max(reach, i + nums[i]);
}
return true;
}
};/**
* @param {number[]} nums
* @return {boolean}
*/ var canJump = function(nums) {
let reach = 0;
for (let i = 0; i < nums.length; i++) {
if (i > reach) return false;
reach = Math.max(reach, i + nums[i]);
}
return true;
};