Jump Game

35 min · canJump()

A single zero can turn a promising route into a dead end. The real question is whether you ever have to land on it.

You're given an array nums. At index i, the value nums[i] is the maximum number of positions you may jump forward from there. Starting at index 0, return true if some sequence of jumps can reach the last index; otherwise return false.

A jump may be any length from 1 through the current maximum. You don't have to use the full jump, and reaching the last index is enough — you never need to jump beyond it.

Constraints

  • 1 <= nums.length <= 10_000
  • 0 <= nums[i] <= 100_000

Hints

Mark the safe places

Work backward and mark an index safe when it can jump to another safe index. This gives a direct solution, even if it checks many destinations repeatedly.

Keep a frontier

While scanning from the start, every reachable index may extend one shared frontier, the furthest index any jump sequence has reached so far.

Know when you're stuck

If the scan arrives at index i but the frontier is smaller than i, no earlier reachable position can land there. If the frontier reaches the last index, you're done.

Follow-up

Can you adapt the same frontier idea to count the minimum number of jumps when the last index is guaranteed to be reachable?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  3,
  1,
  1,
  4
]
Expected
true
Why
jump to index 1, then reach the last index

Example 2

ready
Input
nums = [
  3,
  2,
  1,
  0,
  4
]
Expected
false
Why
every route gets trapped at the zero on index 3

Example 3

ready
Input
nums = [
  1,
  1,
  0
]
Expected
true
Why
two one-step jumps reach the final zero

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite