Continue learning
Practice related DSA questions in the same topic.
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.
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 jumpsFinish the current jump frontier at 0.
Finish the current jump frontier at 0.
Count bus transfers by expanding all stops available with the same number of tickets.
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
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
Incrementing jumps for every position counts alternatives as extra trips.
Can you reconstruct an actual shortest sequence of jumps?