Jump Game II

MediumGreedy · Implicit BFS🧩 GreedyLeetCode #45 ↗Updated

Problem

You stand at index 0 of an array nums, where nums[i] is the maximum number of steps you may jump forward from index i (any shorter jump is also allowed). Return the fewest jumps needed to land on the last index. The last index is guaranteed to be reachable.
Input[2,3,1,1,4]Output2
Input[2,3,0,1,4]Output2

1 ≤ n ≤ 104  ·  0 ≤ nums[i] ≤ 1000  ·  the last index is always reachable

Try it yourself

Java
class Solution {
    public int jump(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Indices reachable with exactly k jumps form a contiguous window. Treat each window as a BFS level: while scanning it, track the farthest index any of its cells can reach — that becomes the right edge of the next level.
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 ForceRecursion over Every Jump Length

Time O(2n)Space O(n)

From index i, try every jump length 1..nums[i] and take 1 + min over the results; reaching the last index costs 0. It explores every path, so it is correct, but the same suffixes are recomputed over and over.

Java
public int jump(int[] nums) {
    return minJumps(nums, 0);
}

private int minJumps(int[] nums, int i) {
    int n = nums.length;
    if (i == n - 1) return 0;
    int best = Integer.MAX_VALUE;
    for (int j = i + 1; j <= Math.min(n - 1, i + nums[i]); j++) {
        int sub = minJumps(nums, j);
        if (sub != Integer.MAX_VALUE) best = Math.min(best, sub + 1);
    }
    return best;   // MAX_VALUE = last index unreachable from i
}

Clear recurrence, but exponential — only usable for tiny arrays.

At a glance

LevelApproachTimeSpace
Brute ForceRecursion over Every Jump LengthO(2n)O(n)
Better1-D DP (Relax Forward)O(n2)O(n)
OptimalGreedy BFS LevelsO(n)O(1)
Common pitfalls
  • Looping to n-1 — counts an extra jump when end lands on the last index.
  • Always jumping to the largest nums[i] — the best next cell is the one reaching farthest.
  • Returning 1 for n == 1 — you start on the last index, so the answer is 0.
Interview tips
  • Frame it as BFS on indices; then show the levels are contiguous, so no queue is needed.
  • Mention the recursion → DP → greedy progression and each complexity.
  • Contrast with Jump Game I (55), which only tracks the farthest reach.
Pattern
Greedy range expansion (implicit BFS) → minimum steps when each level is a contiguous interval.
My notes saved in this browser