Jump Game II

mediumGreedy & Intervals20 stepsJava · Python · C++

Find the fewest jumps to reach the end. Think in levels: all indices reachable with k jumps form a window. While scanning the current window, track the farthest you could get with one more jump; when you reach the window's end, take a jump and move to the next window.

▶ Watch the animated trace

Traced input: nums = [2, 3, 1, 1, 4] → 2. Original problem: neetcode.io/problems/jump-game-ii

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

One pass.

Key idea

Common mistakes

Solution

Java
int jump(int[] nums) {
    int jumps = 0, end = 0, far = 0;
    for (int i = 0; i < nums.length - 1; i++) {
        far = Math.max(far, i + nums[i]);
        if (i == end) {
            jumps++;
            end = far;
        }
    }
    return jumps;
}
Python
def jump(nums: List[int]) -> int:
    jumps = end = far = 0
    for i in range(len(nums) - 1):
        far = max(far, i + nums[i])
        if i == end:
            jumps += 1
            end = far
    return jumps
C++
int jump(vector<int>& nums) {
    int jumps = 0, end = 0, far = 0;
    for (int i = 0; i + 1 < (int)nums.size(); i++) {
        far = max(far, i + nums[i]);
        if (i == end) {
            jumps++;
            end = far;
        }
    }
    return jumps;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Single element
Already at the end.
nums = [0]0
Ones
One step at a time.
nums = [1, 1, 1, 1]3
One big jump
The first jump reaches the end.
nums = [4, 1, 1, 1, 1]1
← Insert IntervalGas Station →