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
| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| a[i] | 2 | 3 | 1 | 1 | 4 |
| layer | 0 | 1 | 1 | 2 | 2 |
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
- Jump Gamemediumguide ready
- Minimum no. of Jumps to reach end of an arraymediumguide ready