Skip to content
DSA Patterns
Menu
Language
GreedyLC #451 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumgreedy

Jump Game II

Problem (restated)

Minimum jumps to reach last index (guaranteed reachable).

Intuition

Level-by-level: within current jump range, track farthest next end; when i hits end, jump++.

Approaches

Range BFS greedy

Unverified
Time O(n)Space O(1)

Idea. curEnd, far; when i==curEnd, jumps++, curEnd=far.

Walkthrough. [2,3,1,1,4] → 2 jumps.

Trade-offs. Greedy levels vs DP min jumps O(n²).

Solution
export function jump(nums: number[]): number {
  let jumps = 0, curEnd = 0, far = 0;
  for (let i = 0; i < nums.length - 1; i++) {
    far = Math.max(far, i + nums[i]!);
    if (i === curEnd) {
      jumps++;
      curEnd = far;
    }
  }
  return jumps;
}
export function jump(nums: number[]): number {
  let jumps = 0, curEnd = 0, far = 0;
  for (let i = 0; i < nums.length - 1; i++) {
    far = Math.max(far, i + nums[i]!);
    if (i === curEnd) {
      jumps++;
      curEnd = far;
    }
  }
  return jumps;
}

Template connection

Each index before the last expands far to i + nums[i]. When i reaches the current jump’s end, one jump is spent and that end moves to far.

Reflection

  • The farthest jump inside the current window is the next window. The number of windows is the number of jumps.
  • Stop once the last index is already inside this window. [0] answers 0. A jump of 1 at every index is n - 1.
  • The windows are BFS layers. The greedy choice is the max reach inside the window.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Jump Game II: min jumps on [2,3,1,1,4] (end is reachable).

2
0
3
1
1
2
1
3
4
4

jumps=0 · curEnd=0 · far=0

Key:CurrentActive rangeMatchSettled