Jump Game II

35 min · jump()

Reaching the finish isn't the challenge this time — reaching it with the fewest jumps is.

You're given an array nums. From index i, you may jump forward by any distance from 1 through nums[i]. Starting at index 0, return the minimum number of jumps needed to reach the last index.

Every input guarantees that the last index is reachable. A one-element array needs no jump because you already start at the destination.

Constraints

  • 1 <= nums.length <= 10_000
  • 0 <= nums[i] <= 1_000
  • The last index is reachable from index 0.

Hints

Write the expensive truth first

For every landing index, inspect all earlier takeoff indices that can reach it. Store the fewest jumps needed for each landing.

Think in jump counts, not paths

With one jump, you can reach a whole interval. Its frontier is the furthest index reachable with that jump count. Scan the interval to find the next frontier.

Close one layer at a time

Track current_end for the present jump count and farthest for the next. When the scan reaches current_end, spend one jump and promote farthest to the new boundary.

Follow-up

Could you also reconstruct one minimum-jump route, and what extra state would you need to remember its landing indices?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  3,
  1,
  1,
  4
]
Expected
2
Why
jump to index 1, then from there to the end

Example 2

ready
Input
nums = [
  2,
  3,
  0,
  1,
  4
]
Expected
2
Why
the zero doesn't matter when index 1 can jump past it

Example 3

ready
Input
nums = [
  1,
  1,
  1,
  1
]
Expected
3
Why
each move advances exactly one index

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite