Jump Game

MediumGreedy

You start at index 0 of an array nums. From index i you can jump forward by any number of steps from 1 up to nums[i]; a 0 means you cannot move from there.

Return true if you can reach the last index, and false otherwise.

Examples

Example 1
Input:  nums = [1, 3, 0, 0, 2]
Output: true

Jump 1 to index 1, then 3 to index 4, the last one.

Example 2
Input:  nums = [2, 1, 0, 3]
Output: false

Every route lands on index 2, whose 0 lets you go no further.

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • 0 ≤ nums[i] ≤ 10⁵

Stuck?

Hint 1

You do not need to try every route. Track the furthest index you can reach from anything you have reached so far.

Hint 2

Walk the array. If the index you are on is beyond the furthest reach, you are stuck; otherwise stretch the reach to i + nums[i]. Stop once the reach covers the last index.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur