Jump Game II
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Same jump array, you can always reach the end. Return the minimum number of jumps.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Which positions can you reach with exactly one more jump, from the current group?
- Hint 2When you reach the end of the current group, you must have taken a jump.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Metro rides. With one ride you can reach any station in the first zone. From all stations of that zone you scan the farthest station you could get to with a second ride. That farthest point is the end of the second zone. You count a new ride only when you walk past the end of the current zone.
- The obvious way
DP: minimum jumps to each position, checking all earlier positions: O(n²).
- The key insight
Track the end of the current zone (zone_end) and the farthest you can reach from anywhere in this zone (farthest). Walk positions; update farthest. When you arrive at zone_end, take a jump: jumps + 1 and the new zone ends at farthest. Stop before the last position.
- The algorithm
- jumps = 0, zone_end = 0, farthest = 0.
- For each position except the last: farthest = max(farthest, position + leap).
- Position == zone_end? Take a jump: jumps + 1, zone_end = farthest.
- Return jumps.
Watch it run
Examplenums = [2, 3, 1, 1, 4]
At stone 0 the zone ends here, so a jump is needed. The first zone reaches up to stone 2.
jumps = 1, zone ends at 2
Where people slip
- Loop up to the second-last position; including the last can add an extra jump.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def jump(nums):
jumps = 0
zone_end = 0 # last position reachable with 'jumps' jumps
farthest = 0 # farthest reachable with one more jump
for position in range(len(nums) - 1):
farthest = max(farthest, position + nums[position])
if position == zone_end:
jumps += 1 # we must jump to go beyond this zone
zone_end = farthest
return jumpsNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.