Skip to content
ΣDSA Patterns
Menu
Language

Greedy

Guide 1 of 6 · Path 1 of 6

PreviousNext

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

Tested only
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

Greedy jump with range expansion.

Reflection