Minimum Jumps to Reach Home solution explained
Minimum Jumps to Reach Home asks for the fewest moves to get from position 0 to a target on a number line, where a move is a fixed jump forward or a fixed jump backward, two backward jumps in a row are not allowed, and some positions are off limits. Solve it with breadth-first search over the pair (position, whether the last jump was backward), and stop exploring to the right past max(home, largest forbidden) + forward + backward. Return -1 if the search runs dry.
By Evin JohnPublished 8 min read
The setup
A bug lives at position 0 on a number line and wants to get home to position x. Each move is either a jump of exactly a units to the right or exactly b units to the left. It may never land on a negative position or on any position in a forbidden list, and it may not make two backward jumps one after the other. Going past home and coming back is fine. Return the smallest number of jumps that lands exactly on x, or -1 if no sequence works.
| Forbidden | a (forward) | b (back) | x (home) | Answer | One shortest route |
|---|---|---|---|---|---|
| [5, 7] | 3 | 2 | 4 | 3 | 0, 3, 6, 4 |
| [] | 4 | 3 | 1 | 2 | 0, 4, 1 |
| [6] | 5 | 2 | 8 | 3 | 0, 5, 10, 8 |
| [] | 5 | 3 | 4 | 4 | 0, 5, 2, 7, 4 |
| [1, 2] | 2 | 1 | 3 | -1 | The first forward jump lands on 2, which is forbidden, and a backward first jump goes negative |
The fourth row deserves a second look. Home is 4, but neither jump size reaches it directly, so the bug has to go out to 5, back to 2, out to 7 and back to 4. That route alternates directions, which the rule allows. It also visits the same kind of positions a naive search might have already marked as done, which is where most wrong answers come from.
Two things make this harder than a plain BFS
The state is not just the position
Standing on 7 after a forward jump, you may go back. Standing on 7 after a backward jump, you may not. Those are different situations with different futures, so a visited set keyed only by position can wrongly discard a useful path. In the fourth example, a position-only search reaches 7 first by a backward jump from 10 and marks it done; when the route through 2 arrives at 7 with a forward jump, it is thrown away, and the search reports -1 even though 4 jumps work. Track (position, last jump was backward) instead, which at most doubles the number of states.
The line has no right end
Forward jumps can go on forever, so BFS needs a cap or it never terminates on unreachable inputs. Far to the right of home and of every forbidden spot, nothing interesting happens: the board is empty and every position looks like every other one. A bound often quoted for this problem is max(x, largest forbidden) + a + b. The argument behind it is a little fiddly, so in an interview it is fair to state the bound, explain the intuition, and mention that any larger cap is still correct, only slower. We checked the tight cap against one 20 times larger on random inputs and the answers matched in every case.
A slower search to start from
One way to get a correct answer before worrying about efficiency is to compute, layer by layer, the set of states reachable in exactly k jumps, without remembering earlier layers. Stop when a layer contains home. Since the number of distinct states is limited by the cap, a shortest route has at most that many jumps, so you can give up after that many layers.
def fewest_jumps_slow(blocked, fwd, back, home):
bad = set(blocked)
cap = max([home] + blocked) + fwd + back
layer = {(0, False)}
for steps in range(2 * (cap + 1) + 1):
if any(pos == home for pos, _ in layer):
return steps
nxt = set()
for pos, came_back in layer:
if pos + fwd <= cap and pos + fwd not in bad:
nxt.add((pos + fwd, False))
if not came_back and pos - back >= 0 and pos - back not in bad:
nxt.add((pos - back, True))
layer = nxt
return -1Each layer can hold up to S = 2 × (cap + 1) states and there can be up to S layers, so the work grows with the square of the state count. It is still correct, and it served as one of the reference checks for the faster code.
Main approach: BFS with a two-part visited set
Breadth-first search fixes the waste by visiting each state once. Put (0, forward) in the queue with distance 0. When you pop a state, return its distance if the position is home. Otherwise try the forward jump, which is always allowed if it stays within the cap and avoids forbidden spots, and the backward jump, which is allowed only if the last jump was forward and the landing spot is non-negative and not forbidden. Mark each new state visited as you enqueue it.
from collections import deque
def fewest_jumps(blocked, fwd, back, home):
bad = set(blocked)
cap = max([home] + blocked) + fwd + back
seen = {(0, False)}
queue = deque([(0, False, 0)])
while queue:
pos, came_back, steps = queue.popleft()
if pos == home:
return steps
ahead = pos + fwd
if ahead <= cap and ahead not in bad and (ahead, False) not in seen:
seen.add((ahead, False))
queue.append((ahead, False, steps + 1))
behind = pos - back
if not came_back and behind >= 0 and behind not in bad and (behind, True) not in seen:
seen.add((behind, True))
queue.append((behind, True, steps + 1))
return -1function fewestJumps(blocked, fwd, back, home) {
const bad = new Set(blocked);
const cap = Math.max(home, ...blocked) + fwd + back;
// seen[pos * 2 + flag], flag 1 means the last jump went backward
const seen = new Uint8Array((cap + 1) * 2);
let frontier = [[0, 0]];
seen[0] = 1;
for (let steps = 0; frontier.length > 0; steps++) {
const next = [];
for (const [pos, cameBack] of frontier) {
if (pos === home) return steps;
const ahead = pos + fwd;
if (ahead <= cap && !bad.has(ahead) && !seen[ahead * 2]) {
seen[ahead * 2] = 1;
next.push([ahead, 0]);
}
const behind = pos - back;
if (!cameBack && behind >= 0 && !bad.has(behind) && !seen[behind * 2 + 1]) {
seen[behind * 2 + 1] = 1;
next.push([behind, 1]);
}
}
frontier = next;
}
return -1;
}The JavaScript version processes one level at a time, which avoids writing a queue class and keeps the step count in the loop variable. For a very long forbidden list, replace the spread inside Math.max with a loop, since spreading a huge array into a call can exceed the engine's argument limit.
Cost
| Search | Time | Memory | Comment |
|---|---|---|---|
| Layered search, no global visited | About O(C²) | O(C) | Correct, slow |
| BFS on (position, direction) | O(C + f) | O(C + f) | Expected answer |
| BFS on position only | O(C + f) | O(C + f) | Fast but wrong on inputs like the fourth example |
Edge cases
- Home is 0: the answer is 0 jumps, and the check on the first popped state handles it.
- Position a is forbidden: the first move is impossible, so the answer is -1 unless home is 0.
- a equals b: every position you can reach is a multiple of a, so any other home gives -1.
- Home is to the right of every forbidden spot, or to the left of all of them: the cap formula covers both because it takes the larger of the two.
Common mistakes
- Visited keyed by position only. The most frequent bug, shown by the fourth example.
- No upper limit. BFS runs forever when home is unreachable.
- A cap that is too tight, for example stopping at x. Shortest routes often overshoot home and come back, as in the fourth example.
- Allowing a backward first jump from 0. It lands on a negative position, which is not allowed.
- Marking visited on pop instead of push. It still finds the right answer but can enqueue the same state many times.
Talking through it
Fictional example
- Candidate
- All jumps cost one, so the fewest jumps is a shortest path in an unweighted graph. That means BFS.
- Candidate
- The node cannot be just the position, because whether I can jump back depends on the previous move. I will key the visited set by position and a flag for came back.
- Candidate
- Forward jumps never end, so I need a cap. I will use the larger of home and the furthest forbidden spot, plus both jump sizes. Anything beyond that is empty board.
- Interviewer
- And if home cannot be reached?
- Candidate
- The queue empties inside the cap and I return -1.
Keep going in this set
Frog Jump also needs a second piece of state, the last hop length, and shows the same lesson in a dynamic programming setting. Jump Game III is the simpler two-direction search with no rule on consecutive moves. The graph basics behind both are covered in algorithm interview questions.
Drilling it with Natively
Natively can help on practice days: take a screenshot of the statement and it reads the problem and suggests an approach with code, which you can hold up against your own state design afterwards. If you rehearse aloud with a friend playing interviewer, the saved transcript shows whether you explained the cap and the direction flag clearly. See an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Minimum Jumps to Reach Home?
Run breadth-first search from 0 over states (position, whether the last jump was backward). Forward jumps are allowed within a cap; backward jumps only after a forward one, never below 0 or onto a forbidden spot. The first time you reach home, that distance is the answer.
Why is the visited set keyed by position and direction?
Because the rule against two backward jumps in a row means the same position has different options depending on how you arrived. Keying by position alone can discard the only working route.
How far right should the search go?
A commonly used cap is the larger of home and the largest forbidden position, plus the forward and backward jump sizes. A larger cap is still correct, only slower.
What does the problem return when home is unreachable?
It returns -1, which happens when the BFS queue empties inside the cap without ever reaching home.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
