Skip to content
CodeKruPro

Fewest jumps to reach the end of a list

Coding problemMedium-HardAsked in: Amazon

You stand at the first position of a list of non-negative integers. The value at each position is the longest jump you may make from there: from position i you can jump to any position from i + 1 up to i + nums[i].

Return the fewest jumps needed to reach the last position. If the last position cannot be reached, return -1. A list with one value needs 0 jumps.

Examples

Example 1
Input: nums = [2,3,1,1,4]
Output: 2
Jump 1 step to the 3, then 3 steps to the end.
Example 2
Input: nums = [3,2,1,0,4]
Output: -1
Every route lands on the 0 at position 3 and gets stuck.
Example 3
Input: nums = [0]
Output: 0

Constraints

  • The list holds between 1 and 100,000 values
  • Each value is between 0 and 100,000

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in