Skip to content
Onsite

Minimum Jumps to Reach the End

MediumP2Coding

You stand at index 0 of nums. From index i you can jump to any index from i + 1 to i + nums[i]. Return the minimum number of jumps needed to reach the last index, or -1 if it cannot be reached.

An array with one element needs 0 jumps.

Example 1

Input
nums = [2,3,1,1,4]
Output
2
Why
Jump 1 step to index 1, then 3 steps to the end.

Example 2

Input
nums = [1,1,1,1]
Output
3

Example 3

Input
nums = [0]
Output
0

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 1000

Hints

Run checks the 3 visible tests, Submit all 11.