Jump Game

MediumGreedy · Reachability🧩 GreedyLeetCode #55 ↗Updated

Problem

You start at index 0 of an integer array nums. The value nums[i] is the maximum number of steps you may jump forward from index i (any smaller jump is also allowed). Return true if the last index can be reached, otherwise false.
Inputnums = [2,3,1,1,4]Outputtrue (0 → 1 → 4)
Inputnums = [3,2,1,0,4]Outputfalse (every path lands on the 0 at index 3)
Inputnums = [0]Outputtrue

1 ≤ n ≤ 104  ·  0 ≤ nums[i] ≤ 105

Try it yourself

Java
class Solution {
    public boolean canJump(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
You never need to know which path works — only the farthest index reachable so far. Every index up to that frontier is reachable, so sweep once and extend the frontier; if you ever stand beyond it, you're stuck.
PatternGreedy

Instinct An optimisation where one obvious local rule (earliest end, farthest reach, biggest first) never needs undoing - commit to it, then try hard to break it.

Memory hack Grab the best bite now and never look back - but only once a counterexample hunt fails to make you regret it.

Open the Greedy guide →

Approaches

Brute ForceTry Every Jump (Recursion)

Time O(2n)Space O(n)

From index i, try every jump length 1..nums[i] and recurse. If any branch lands on the last index, the answer is yes. Without memory the same index is re-solved again and again, so the number of paths explodes.

Java
public boolean canJump(int[] nums) {
    return reach(nums, 0);
}

private boolean reach(int[] nums, int i) {
    if (i >= nums.length - 1) return true;
    int farthest = Math.min(i + nums[i], nums.length - 1);
    for (int next = farthest; next > i; next--) { // try long jumps first
        if (reach(nums, next)) return true;
    }
    return false;
}

Direct translation of the rules; exponential, only usable for tiny arrays.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every Jump (Recursion)O(2n)O(n)
BetterBottom-Up DP over Good IndicesO(n · max(nums))O(n)
OptimalGreedy Farthest ReachO(n)O(1)
Common pitfalls
  • Only trying the maximum jump each time — a shorter jump may be the one that works.
  • Forgetting that a single-element array is already at the end (true).
  • Checking i > reach after updating reach — lets you jump from an unreachable cell.
Interview tips
  • Start with the recursion tree, point out repeated sub-problems, then move to DP.
  • Explain why tracking one number suffices: reachable indices form a prefix.
  • Mention Jump Game II (min jumps) uses the same frontier idea, BFS-by-layers style.
Pattern
Greedy frontier → when reachable states always form a contiguous prefix, track only its right edge.
My notes saved in this browser