Minimum Forward Jumps
Find the fewest jumps from the first index to the last, or -1 if unreachable. Each number is the maximum jump length from that index.
Find the fewest jumps from the first index to the last, or -1 if unreachable. Each number is the maximum jump length from that index.
Input and constraints
- Supply at least one value.
- Each value must be nonnegative.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): reach = 0 end = 0 jumps = 0 i = 0 while (i < (len(values) - 1)): reach = max(reach, (i + values[i])) if (i == end): if (reach == end): return -1 end = reach jumps = (jumps + 1) i = (i + 1) return jumpsVisualizer
Step 1 of 5Inspect the current state
Finish the current jump frontier at 0.
Variable watch
Step explanation
Finish the current jump frontier at 0.
Worked explanation
Count bus transfers by expanding all stops available with the same number of tickets.
Guided solution
All positions in a current frontier use the same jump budget. Accumulate the next frontier before spending another jump.
O(n) time · O(1) auxiliary space
Examples
Worked example · {"values":[2,3,1,1,4],"target":0} ⇒ 2
Edge case 1 · {"values":[0,2],"target":0} ⇒ -1
Edge case 2 · {"values":[0],"target":0} ⇒ 0
Progressive hints
Hint 1
Count bus transfers by expanding all stops available with the same number of tickets.Hint 2
All positions in a current frontier use the same jump budget. Accumulate the next frontier before spending another jump.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Incrementing jumps for every position counts alternatives as extra trips.
Interview follow-up
Can you reconstruct an actual shortest sequence of jumps?