CodingNodes / Greedy / Jump Game II System design Space play · ←→ step · R restart

Problem

You stand on index 0 of an array nums. From index i you may jump to any index from i + 1 up to i + nums[i].

The last index is guaranteed to be reachable. Return the minimum number of jumps needed to get there.

Constraints

  • 1 ≤ nums.length ≤ 10000
  • 0 ≤ nums[i] ≤ 1000
  • The last index is always reachable

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass over the array, with constant work per index.

Space: Only jumps, end, farthest and the loop index are kept.

Treat each jump as a level of a breadth-first search. The indices reachable with the current number of jumps end at end. While scanning them, track the farthest index any of them can reach. When the scan hits end, one more jump is needed and the next window ends at farthest.