~/problems / Greedy

Jump Game II

medium ~20 min

Write min_jumps(nums: list[int]) -> int.

You start at index 0. From index i you may jump forward by any distance from 1 to nums[i]. Return the minimum number of jumps needed to land on the last index. The input is guaranteed to make the last index reachable.

min_jumps([2, 3, 1, 1, 4])   # 2   (0 -> 1 -> 4)
min_jumps([1, 1, 1, 1])      # 3
min_jumps([4, 0, 0, 0, 0])   # 1
min_jumps([0])               # 0   (already on the last index)

Constraints: 1 <= len(nums) <= 2 * 10^5, 0 <= nums[i] <= 10^5.

A DP that tries every jump from every index is O(n · max(nums)) and fails the large test; aim for O(n).

Show hint

the indices reachable with exactly k jumps (and no fewer) form one contiguous window. How do you get the next window from the current one?

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc