Minimum Jumps to Reach Home

Find the fewest forward and backward jumps that take a bug from position 0 to its home at x.

A bug starts at position 0 on a number line and wants to get home, to position x. Each jump goes exactly a positions forward, to the right, or exactly b positions backward, to the left. The bug cannot jump backward twice in a row, cannot land on a position listed in forbidden, and cannot land below 0. It may jump past x. Return the smallest number of jumps that takes it to x, or -1 if no sequence of jumps does.

Example 1
Input: forbidden = [14, 4, 18, 1, 15], a = 3, b = 15, x = 9
Output: 3
Explanation: 0 → 3 → 6 → 9.
Example 2
Input: forbidden = [8, 3, 16, 6, 12, 20], a = 15, b = 13, x = 11
Output: -1
Example 3
Input: forbidden = [1, 6, 2, 14, 5, 17, 4], a = 16, b = 9, x = 7
Output: 2
Explanation: 0 → 16 → 7. Going past x and coming back is allowed.
Solution

The Idea

Think of a row of stepping stones numbered 0, 1, 2 and so on, with some of them cracked. The bug stands on stone 0, and its home is stone x. It has only two moves: a hop of a stones to the right, or a hop of b stones back to the left, never two hops back in a row. The cracked stones are the forbidden positions.

In Example 1 the forward hop is 3, so the bug goes 0, 3, 6, 9 and is home after three jumps, without touching the forbidden stones 1, 4, 14, 15 and 18. Example 3 is less direct. Home is 7, the forward jump is 16, and stones 1, 2, 4, 5 and 6 are forbidden. A backward jump from 0 would land on -9, below 0. The only way home is to overshoot: forward to 16, then back 9 to 7.

So a route may wander past home and come back, and the number of possible routes grows with every jump. How can we be sure a route is the shortest one, without trying them all?

Count in rounds. List every stone the bug can stand on after one jump, then every stone after two jumps, and so on. The first round that contains x gives the answer, because no earlier round did. Look at the picture below, which shows Example 3.

Example 3 on a number line from 0 to 32, with forbidden stones 1, 2, 4, 5, 6, 14 and 17. Jump 1 goes forward 16 from 0 to 16. Jump 2 goes either forward 16 to 32, past home, or backward 9 to 7, which is home.

After jump 1 the bug can only be on stone 16, since the backward jump from 0 is ruled out. Jump 2 offers two stones: forward again to 32, past home, or backward 9 to 7. Stone 7 is home, so the answer is 2, and round 1 had no way to be home.

This round-by-round search is called breadth-first search, or BFS for short: it looks at everything one jump away before anything two jumps away. Whenever every step costs the same, as every jump does here, it finds the fewest steps.

Solution Approach

Turning that idea into code means settling three things: how to keep the rounds in order, what to remember about each stone, and how far to the right the search may go.

Searching round by round

Why not simply try every sequence of jumps? Each jump has up to two choices, so there can be 2k sequences of k jumps: over 1,000 for ten jumps and over a million for twenty. Many of them end on the same stones, so most of that work is repeated.

Breadth-first search uses a queue instead, a line where new entries join at the back and are taken from the front. The queue starts with stone 0. The search takes an entry from the front and adds the stones its two jumps reach to the back. Because stones join behind the current round, every stone of round 2 is taken before any stone of round 3.

To know when a round ends, the search notes how many entries the queue holds when the round begins and takes exactly that many. Everything added meanwhile belongs to the next round.

What to remember about each stone

When can the search skip a stone it has reached before? Normally at once, because the earlier visit came in the same round or an earlier one. The rule about backward jumps makes it less simple. A bug that arrived on a stone by a backward jump cannot jump backward next, while one that arrived by a forward jump can. The same stone offers different moves depending on how the bug got there.

So the search treats each stone as two places: the stone reached by a forward jump, and the stone reached by a backward jump. Each of these is called a state. The search marks each state when it first reaches it and adds every state to the queue at most once. Keeping only one mark per stone would throw away the forward arrival whenever the backward arrival came first, and with it the backward jump that only the forward arrival may take.

How far to the right to search

Where should the search stop? Backward jumps cannot go below 0, but forward jumps have no end. If home cannot be reached, a search without a right edge would keep jumping right forever.

The edge used here, called limit, is the largest of x and the forbidden positions, plus a + b. It can be shown that a shortest route never needs to go past it. Roughly, beyond the last forbidden stone and home nothing is in the way, so a route that wanders further right can reorder its jumps and stay within a + b of that point. In Example 3, home is 7 and the largest forbidden position is 17, so limit is 17 + 16 + 9 = 42. Stone 32 is inside it, and the next forward jump, to 48, is not taken.

Java Solution

The method minimumJumps works in these steps:

  1. First, put the forbidden positions into blocked, a HashSet, so checking a stone takes one step. The same loop finds furthest, the largest of x and the forbidden positions.
  2. Set limit to furthest + a + b. Then create visited, a boolean array with a row for every stone from 0 to limit and two columns: column 0 marks the stone as reached forward, column 1 as reached backward.
  3. Create queue, an ArrayDeque (Java's array-based queue) of two-number entries: the position, then 1 if the bug got there by a backward jump and 0 otherwise. Start it with {0, 0} and mark visited[0][0].
  4. Run the rounds with two loops, one inside the other. The outer loop counts jumps, the round number. The inner loop takes size entries, as many as the queue held when the round began. For each entry state, if its position pos is x, return jumps.
  5. Try the forward jump to forward = pos + a. If it is at most limit, not in blocked and not yet reached forward, mark it and add it to the queue with a 0.
  6. Try the backward jump to back = pos - b, but only if state[1] is 0, meaning the bug did not just jump back. If back is at least 0, not in blocked and not yet reached backward, mark it and add it with a 1.
  7. If the queue runs empty, no round reached x, so return -1.

The main method runs the three examples, a home at 0, and a case with no forbidden stones, a = 6, b = 1 and x = 26.

Java
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;

public class MinimumJumpsToReachHome {

    public static int minimumJumps(int[] forbidden, int a, int b, int x) {
        Set<Integer> blocked = new HashSet<>();
        int furthest = x;
        for (int f : forbidden) {
            blocked.add(f);
            furthest = Math.max(furthest, f);
        }
        int limit = furthest + a + b;             // going further right never helps
        // visited[pos][0]: reached by a forward jump, visited[pos][1]: by a backward jump
        boolean[][] visited = new boolean[limit + 1][2];
        Queue<int[]> queue = new ArrayDeque<>();  // each entry: {position, cameBack}
        queue.add(new int[] {0, 0});
        visited[0][0] = true;
        for (int jumps = 0; !queue.isEmpty(); jumps++) {
            for (int size = queue.size(); size > 0; size--) {   // one round of jumps
                int[] state = queue.poll();
                int pos = state[0];
                if (pos == x) {
                    return jumps;
                }
                int forward = pos + a;
                if (forward <= limit && !blocked.contains(forward) && !visited[forward][0]) {
                    visited[forward][0] = true;
                    queue.add(new int[] {forward, 0});
                }
                int back = pos - b;
                if (state[1] == 0 && back >= 0 && !blocked.contains(back) && !visited[back][1]) {
                    visited[back][1] = true;      // no second backward jump from here
                    queue.add(new int[] {back, 1});
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(minimumJumps(new int[] {14, 4, 18, 1, 15}, 3, 15, 9));
        System.out.println(minimumJumps(new int[] {8, 3, 16, 6, 12, 20}, 15, 13, 11));
        System.out.println(minimumJumps(new int[] {1, 6, 2, 14, 5, 17, 4}, 16, 9, 7));
        System.out.println(minimumJumps(new int[] {5}, 2, 1, 0));
        System.out.println(minimumJumps(new int[] {}, 6, 1, 26));
    }
}

Running it prints:

Output
3
-1
2
0
9

The 3, -1 and 2 at the top match the three examples. For Example 2 the queue ran empty before any round reached 11, so the method fell through to -1. The 0 in the fourth line is a home at the start: the first entry taken from the queue is already at x, so the method returns before any jump.

Look at the last line, 9. The route is 0, 6, 5, 11, 10, 16, 15, 21, 20, 26: forward and backward in turn, ending with a forward jump. A version with one mark per stone returns -1 for the same input. There, stone 11 is first reached backward, from 12, and the forward arrival from 5 is thrown away, though only it may jump back to 10.

Complexity

The search handles each state at most once, and there are two states for every stone from 0 to limit.

  • Time: O(L + F), where L is limit and F the number of forbidden positions. Building blocked takes F steps, and each of the 2(L + 1) states is added to the queue and taken from it at most once, with a fixed amount of work each time.
  • Space: O(L + F). The visited array has 2(L + 1) marks, the queue never holds more states than that, and blocked stores F positions.

Breadth-first search over states rather than plain positions also solves Word Ladder.