Jump Game II

Find the fewest jumps from the first index of an array to the last, by counting rounds of reachable indexes.

You stand at index 0 of an array of integers nums. The number nums[i] is the longest jump you can make from index i: you may move forward by any number of places from 1 up to nums[i]. Return the fewest jumps needed to reach the last index. The input always lets you reach it.

Example 1
Input: nums = [2, 3, 1, 1, 4]
Output: 2
Explanation: jump from index 0 to index 1, then from index 1 to the last index.
Example 2
Input: nums = [2, 3, 0, 1, 4]
Output: 2
Solution

The Idea

Picture a row of stepping stones across a stream, numbered 0 to 4 from your bank, just like the indexes of nums. Each stone carries a number: from that stone you can leap forward at most that many stones, and you may also leap shorter. In Example 1 the numbers are 2, 3, 1, 1 and 4, and you want to reach stone 4 in as few leaps as possible.

From stone 0, the 2 lets you land on stone 1 or stone 2. Leaping as far as possible sounds right, but stone 2 carries a 1, so you go on to stone 3 and then stone 4: three leaps. The shorter first leap lands on stone 1, whose 3 reaches stone 4 directly: two leaps. So the farthest landing spot is not always the best one. How can you tell where to land without trying every route?

Stop choosing stones and count rounds instead. Before any leap you stand on stone 0; call that round 0. After one leap you can stand on stone 1 or stone 2, which is round 1. Round 2 is every stone you can reach with a second leap from round 1, and so on. Look at the picture below.

The array 2, 3, 1, 1, 4. Index 0 is round 0. Its leaps reach indexes 1 and 2, round 1, reachable with 1 jump. From round 1 the farthest reach is 1 + 3 = 4, so round 2 is indexes 3 and 4, reachable with 2 jumps.

The grey box, index 0, is round 0. The blue arrows show its leaps to indexes 1 and 2, the boxes bracketed as round 1, reachable with 1 jump. From index 2, the pale arrow reaches index 3 at most. The orange arrow from index 1 goes further, to 1 + 3 = 4. So round 2, in teal, ends at index 4, the last index, and the answer is two jumps.

Each round is a block of neighbouring indexes with no gaps, because a leap may be shorter than its number allows: whoever can reach index 4 can also reach index 3. So a round is fully described by its last index. The next round ends at the farthest point that any index of the current round can reach, which is the largest value of index plus its number in that round.

Example 2 changes the number at index 2 to 0. Round 1 is still indexes 1 and 2, and index 1 still reaches 1 + 3 = 4, so the 0 does no harm and the answer is again 2.

Exploring in rounds like this, with every index one jump away before any index two jumps away, is called breadth-first search, or BFS. Here no list of indexes is needed, because each round is one block. Settling each round by its farthest reach, without ever going back to change an earlier round, is a greedy choice. Note that it picks the round that reaches farthest, not the longest single leap, which failed from stone 0.

Solution Approach

A simple way looks back from every index, but it is slow. The rounds avoid that, and turning them into code means settling three things: how to describe a round with two numbers, when to count a jump, and where the loop stops.

Looking back from every index

Why not work out the fewest jumps to each index in turn? For each index, look back at every earlier index that can reach it, and take the smallest jump count among them, plus one. That gives the right answer, but each index looks back over all the earlier ones, so an array of n numbers takes about n²/2 checks. The rounds need a single pass, because each round is settled once and never looked at again.

Describing a round with two numbers

What must the code remember about a round? A round has no gaps, so its last index is enough, and the code keeps it in currentEnd. A loop moves an index i along the array. While i walks through the current round, the code keeps the largest i + nums[i] seen so far in farthest. That is where the next round will end.

When to count a jump

When does the current round run out? When i reaches currentEnd, every index of the round has offered its reach, so farthest is final. The code then adds one to the jump count, jumps, and moves currentEnd to farthest, which starts the next round. At i = 0 this happens straight away, because round 0 is index 0 alone.

Where the loop stops

Should the loop visit the last index too? Standing on the last index needs no further jump, so the loop stops one index before it. If a round ends exactly on the last index, i never gets there, and no extra jump is counted.

Java Solution

The method jump works in these steps:

  1. First, set three counters to 0: jumps, the jumps counted so far; currentEnd, the last index of the round reached with that many jumps; and farthest, the farthest index reachable with one jump more.
  2. Walk through the array with one loop, moving i from index 0 up to the index just before the last one.
  3. At each i, set farthest to Math.max(farthest, i + nums[i]), so it grows when this index reaches further.
  4. When i equals currentEnd, the round is used up: add 1 to jumps and set currentEnd to farthest.
  5. After the loop, return jumps.

The main method runs both examples, an array of one number, an array whose first number already reaches past the end, and an array of ones, where every jump moves one place.

Java
import java.util.Arrays;

public class JumpGameII {

    public static int jump(int[] nums) {
        int jumps = 0;
        int currentEnd = 0;   // last index of the round reached with "jumps" jumps
        int farthest = 0;     // farthest index reachable with one jump more
        for (int i = 0; i < nums.length - 1; i++) {
            farthest = Math.max(farthest, i + nums[i]);
            if (i == currentEnd) {    // the whole round is scanned: one more jump
                jumps++;
                currentEnd = farthest;
            }
        }
        return jumps;
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {2, 3, 1, 1, 4},
            {2, 3, 0, 1, 4},
            {0},
            {5, 1, 1},
            {1, 1, 1, 1}
        };
        for (int[] nums : inputs) {
            System.out.println(Arrays.toString(nums) + " -> " + jump(nums));
        }
    }
}

Running it prints:

Output
[2, 3, 1, 1, 4] -> 2
[2, 3, 0, 1, 4] -> 2
[0] -> 0
[5, 1, 1] -> 1
[1, 1, 1, 1] -> 3

For [2, 3, 1, 1, 4] the method returns 2, the two rounds in the picture. i meets currentEnd at index 0 and again at index 2, the last index of round 1. At index 3 no jump is counted, because currentEnd is 4 by then. [2, 3, 0, 1, 4] also gives 2, since index 1 still reaches index 4.

[0] gives 0: you start on the last index, so the loop never runs. [5, 1, 1] gives 1, because at index 0 farthest becomes 5, past the last index 2. In [1, 1, 1, 1] every round holds a single index, so each of the 3 jumps moves one place.

The loop bound nums.length - 1 matters. With i < nums.length instead, the loop also visits the last index. In Example 1, i then meets currentEnd at index 4 and counts a third jump, so that version returns 3, and for [0] it returns 1 instead of 0.

Complexity

The method makes one pass over the array and keeps three numbers.

  • Time: O(n), because the loop visits each of the n indexes except the last once, and does one Math.max and one comparison at each.
  • Space: O(1), because each round is a block with no gaps, so currentEnd and farthest describe it without any list of indexes to visit.

The same rounds of farthest reach also solve Minimum Number of Taps to Open to Water a Garden, where each tap covers a stretch of a line.