Greedy Algorithms · Array · Minimum jumps

Jump Game II Visualizer

What is Jump Game II

Each element nums[i] is the maximum forward jump from index i. Return the minimum number of jumps to reach the last index. The classic problem promises that the last index is reachable.

Example. nums = [2, 3, 1, 1, 4] returns 2. Jump from index 0 to index 1, then from index 1 to index 4.

Input:  2 3 1 1 4
Output: 2

A second route, 0 to 1 to 4 on [2, 3, 0, 1, 4], is also 2 jumps. Jumping 0 to 2 lands on a 0 and wastes a jump.

Constraints. 1 ≤ n ≤ 104. The picture keeps n at 12.

Approach

Breadth-first jumpsEvery index you can reach with exactly k jumps is one level. A queue finds the minimum, and it still touches each index a constant number of times.
WindowsThe same levels can be drawn without a queue. The current window is the range of the jump you are in. While you walk it, remember the farthest index the next jump can reach. When the index hits the end of the window, spend one jump and open that next range.

Interactive visualization

Step through the greedy choice

The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.

if n <= 1: return 0
jumps = 0, end = 0, far = 0
for i = 0 to n - 2:
far = max(far, i + nums[i])
if i == end and far <= end: stuck
if i == end: jumps += 1, end = far
return jumps
Step 0 Answer —

Complexity

PieceCostWhy
TimeO(n)Each index updates farthest at most once.
SpaceO(1)The window end, farthest index, and jump count are enough.
Greedy choiceExtend the windowThe farthest landing in this window is the best place for the next jump to end.

Implementation

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