0:00 / 0:00

Now count the fewest hops to the end. Treat each jump as a window of reachable spots, and only jump when you walk off its edge.

▼

The problem

You start at index 0 of an array nums; nums[i] is the farthest you can jump forward from index i. The last index is always reachable. Return the fewest jumps to reach it.

Example: nums = [2, 4, 1, 2, 1, 1, 1] → 3.

TRY IT ON LEETCODE ▶

The solution

def jump(nums):
    jumps = end = farthest = 0
    for i in range(len(nums) - 1):
        farthest = max(farthest, i + nums[i])
        if i == end:
            jumps += 1
            end = farthest
    return jumps

Transcript

Jump Game Two. You start on the first spot of a row of numbers. Each number is the farthest you can jump from that spot. The last spot is always reachable. What's the fewest jumps to get there?

Take two, four, one, two, one, one, one. Grab the biggest jump first, two steps onto a one, and it takes four jumps. Hop one step onto the four instead: it carries you to index five, and one more hop finishes. Three jumps. The longest hop isn't always the best.

You could try every route. This row has eight, and longer rows have exponentially more. Or fill a table of the fewest jumps to each spot, checking every spot before it. That's twenty-one checks here: n squared time.

The greedy trick: think in levels, like breadth-first search. Zero jumps: you're on the start. One jump reaches a window, index one and two. Two jumps reach the next window, which ends at the farthest any spot in the first can reach: index five. Three jumps reach the end. So walk left to right, tracking the farthest reach. When you hit the window's end, you must jump. Count it, and the next window ends at the farthest.

In code, jumps, end and farthest start at zero. Loop up to the second last index, since standing on the last needs no jump. Stretch farthest to i plus the jump. If i equals end, add a jump and move end to farthest.

Back to our row. Index zero reaches two, and it's the window's end. Jump one; the window now ends at two. Index one reaches five. Index two is the end. Jump two; the window ends at five. Index three reaches five, and so does index four. Index five reaches six, and it's the end. Jump three; the window ends at six, the last index. Answer: three jumps.

Every index is visited once, so it's O of n time. Just three numbers to remember: constant space.

Don't choose each jump. Fill the window, then leap. That's Jump Game Two.