CodeArchon

mediumGreedyAmazon

Minimum Hops

The platformer finds the FEWEST jumps to clear the stage, given per-tile max jump distances.

Given a jump-length array, return the minimum number of jumps to reach the last index (assume reachable).

Choose approach

2
0
i
3
1
1
2
endfar
1
3
4
4
1/5
Narrationstep 1 of 5

i=0: farthest=2, jumps=1, end=2.

1def jump(nums):
2 jumps = end = farthest = 0
3 for i in range(len(nums) - 1):
4 farthest = max(farthest, i + nums[i])
5 if i == end:
6 jumps += 1; end = farthest
7 return jumps
Variables
i=0
farthest=2
jumps=1
end=2

How to think about it

  1. Each 'jump' consumes a frontier.
  2. Greedy = always jump to the farthest-reaching option.

Edge cases to catch in interview

  • Length 1 -> 0.
  • Length 2 with nums[0] ≥ 1 -> 1.

Examples

Example 12
{"values":[2,3,0,1,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed