Algo-Sim › Greedy

Jump Game II

Medium · Greedy · step through it in Java, Python and C++ on your own input

The last index is always reachable; find the fewest jumps. Scan window by window like BFS levels, jumping when the window runs out.

Problem

As in Jump Game, nums[i] is the longest jump from index i, and you start at index 0. The last index is guaranteed to be reachable. Return the minimum number of jumps needed to get there.

Constraints

Edge cases to test

Follow-up questions

Why is this BFS without a queue?
Indices reachable in k jumps form a contiguous window, so the next window is just [end + 1, farthest]: O(n) time, O(1) space.
What if some cells are unreachable?
If a window ends with farthest ≤ the current index, return −1.

Solution

Java

public int jump(int[] nums) {
    int jumps = 0, end = 0, farthest = 0;
    for (int i = 0; i < nums.length - 1; i++) {
        farthest = Math.max(farthest, i + nums[i]);
        if (i == end) {
            jumps++;
            end = farthest;
        }
    }
    return jumps;
}

Python

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int jump(vector<int> &nums) {
        int jumps = 0, end = 0, farthest = 0;
        for (int i = 0; i < int(nums.size()) - 1; i++) {
            farthest = std::max(farthest, i + nums[i]);
            if (i == end) {
                jumps++;
                end = farthest;
            }
        }
        return jumps;
    }
};

More Greedy problems