Learn / Greedy

Jump game

Track the farthest index you can reach. Walk forward; if you ever stand beyond it, the end is unreachable. For the fewest jumps, think in layers like a breadth-first search: everything reachable with j jumps forms a window, and the farthest point reachable from that window ends the next layer.

How to recognise it

  • Each value says how far you may jump from there.
  • The question is whether the end can be reached, or in how few jumps.
  • A reachable range that grows as you scan.

Can you reach the end?

farthest = 0
for i in 0..n-1:
    if i > farthest: return false
    farthest = max(farthest, i + nums[i])
return true

Fewest jumps

jumps = 0; end = 0; farthest = 0
for i in 0..n-2:
    farthest = max(farthest, i + a[i])
    if i == end:                 # this layer is finished
        if farthest <= i: return -1
        jumps += 1; end = farthest
i01234
a[i]23114
layer01122

Common mistakes

  • Looping to the last index in the fewest-jumps version, which counts a jump that is not needed.
  • Forgetting the unreachable case.

Problems

0 of 2 solved

Check yourself

nums = [3, 2, 1, 0, 4]. Can you reach the end?

For [2, 3, 1, 1, 4], what is the fewest number of jumps?

Why is the fewest-jumps greedy like BFS?