Jump Game

Decide whether jumps along an array can carry you from its first index to its last.

Given an array nums, you start at index 0. Each value nums[i] is the longest jump you may make from index i: any distance from 1 up to that value, or no jump at all if it is 0. Return true if you can reach the last index, and false otherwise.

Example 1
Input: nums = [2, 3, 1, 1, 4]
Output: true
Explanation: jump 1 step to index 1, then 3 steps to the last index.
Example 2
Input: nums = [3, 2, 1, 0, 4]
Output: false
Explanation: every path lands on index 3, whose jump length is 0.
Solution

The Idea

Picture a row of stepping stones across a stream. Each stone has a number painted on it: the most stones you may leap forward from there. You stand on the first stone and want to land on the last one. The array nums is that row, and index i is stone i.

In Example 1, [2, 3, 1, 1, 4], index 0 lets you jump 1 or 2. Jump 1 to index 1, whose 3 carries you to index 4, the last index. In Example 2, [3, 2, 1, 0, 4], index 0 lets you land on index 1, 2 or 3. From index 1 you can land on 2 or 3, and from index 2 only on 3. Index 3 holds 0, so every path stops there, and index 4 stays out of reach.

Even five numbers give several paths to follow, and a longer array gives far more. Do we really need to know which path works, or only how far some path can get?

How far is enough. If you can reach an index, you can reach every index before it too. A path to it either lands on each earlier index or jumps over it, and a jump that passes over an index could be made shorter to land there instead. So the indices you can reach always form one unbroken block, from index 0 up to an index we will call the farthest reach.

Example 1: from index 0 a jump reaches index 2, and from index 1 a jump of 3 reaches index 4, the last index, so the farthest reach becomes 4 and the answer is true. Example 2: every jump from indexes 0, 1 and 2 ends at index 3 or before, so the reachable block stops at farthest reach 3 and index 4 cannot be reached.

Look at the picture above. In the top row, labelled "Example 1", the longest jump from index 0 lands on 0 + 2 = 2, and the one from index 1 lands on 1 + 3 = 4, the last index. That row reads "farthest reach becomes 4: true". In the bottom row, "Example 2", the shaded box around index 0 to index 3, labelled "reachable block: farthest reach = 3", is the reachable block. Every jump ends at index 3 or before, so the farthest reach stays 3, and index 4 is marked "cannot be reached".

So one number describes every index we can reach. Walking the array from left to right, each index inside the block may push the farthest reach further, and we never go back to compare paths. Taking the best step we can see at each index and never reconsidering it is what puts this problem among the greedy methods.

Solution Approach

After a look at why following paths is slow, three things need settling: what to remember while walking the array, whether to check an index before using its jump, and when the walk may stop.

Following every path

Why not try the paths one by one? A search can try each jump length from index 0, then each jump length from wherever it lands, and so on. Many paths land on the same index again and again, so the work can grow very fast. Marking each index as reachable, and from each reachable index marking every index its jump can land on, avoids the repeats but still takes up to n × n steps for n numbers.

What to remember

What does the walk need to keep? Only the farthest reach, in a variable named farthest. It starts at 0, because at the start you stand on index 0 and have not jumped yet. At each index i, the longest jump lands on i + nums[i], and farthest becomes the larger of that and its old value. The landing spot may lie past the end of the array, which does no harm.

Checking before extending

What if the walk arrives at an index outside the block? In Example 2, the walk arrives at index 4 while farthest is 3. No jump lands on index 4, so the jump length 4 stored there must not count, and the answer is false before that value is read. That is why the check i > farthest comes before the update. Every index after index 4 would be out of reach as well, since the block has no gaps.

When the walk stops

If the walk gets through every index without finding one outside the block, the last index was inside it, and the answer is true. As an optional shortcut, the method could return true as soon as farthest reaches the last index, nums.length - 1. The answer is the same, only found sooner.

Java Solution

The method canJump works in these steps:

  1. First, set farthest to 0: only index 0, the start, is reachable so far.
  2. Walk the array with one loop, moving i from index 0 to the last index.
  3. Inside the loop, check i > farthest first. If it holds, no jump lands on index i, so return false.
  4. Otherwise index i is reachable. Set farthest to Math.max(farthest, i + nums[i]), the larger of the old reach and the landing spot of the longest jump from i.
  5. If the loop finishes without returning, the last index was inside the block, so return true.

The main method runs both examples and five edge cases: a single 0, a 0 first in a longer array, a jump over two zeros, an early stall on a 0, and a long jump that falls short.

Java
import java.util.Arrays;

public class JumpGame {

    public static boolean canJump(int[] nums) {
        int farthest = 0;                    // farthest index reachable so far
        for (int i = 0; i < nums.length; i++) {
            if (i > farthest) {
                return false;                // index i cannot be reached
            }
            farthest = Math.max(farthest, i + nums[i]);
        }
        return true;
    }

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

Running it prints:

Output
[2, 3, 1, 1, 4] -> true
[3, 2, 1, 0, 4] -> false
[0] -> true
[0, 1] -> false
[2, 0, 0] -> true
[1, 0, 1, 0] -> false
[4, 0, 0, 0, 0, 0] -> false

Look at the second line: [3, 2, 1, 0, 4] gives false because, at index 4, the check finds 4 > 3. The line [0] -> true shows that a one-number array needs no jump, since index 0 is already the last index. Right after it, [0, 1] gives false: index 0 allows no jump, so index 1 is never reached.

In [2, 0, 0], the jump of 2 from index 0 lands on the last index and the zeros never matter. In [1, 0, 1, 0] the walk stalls at index 1 and returns false at index 2. The last line has a long first jump of 4, yet farthest stops at 4, one short of the last index, 5.

Why i > farthest and not i >= farthest? The index farthest itself is reachable, so it belongs inside the block. With >=, the check fires at i = 0 straight away, because farthest also starts at 0. Running that version on [2, 3, 1, 1, 4], [0] and [5, 1, 1] printed false for all three.

Complexity

The method does a fixed amount of work at each index and keeps a single number between them.

  • Time: O(n), because the loop looks at each of the n indices at most once, with one comparison and one Math.max, and it stops early at the first index outside the reachable block.
  • Space: O(1), because farthest and the loop index are all the method stores, however long the array is.

Counting the fewest jumps to the last index uses the same farthest reach, one jump at a time: see Jump Game II.