Jump Game III solution explained
Jump Game III asks whether you can reach any position holding a zero when each position lets you jump exactly its value to the left or to the right. Treat every index as a node with at most two outgoing edges and run a depth-first or breadth-first search from the start, marking indexes as visited so the search cannot loop. That is O(n) time and O(n) extra space.
By Evin JohnPublished 8 min read
What the problem asks
You get an array of non-negative integers and a starting index. Standing on index i, you may move to i + a[i] or to i - a[i], as long as you stay inside the array. You can make as many moves as you like. The question is yes or no: can you ever stand on an index whose value is 0? You do not need the path or the number of moves, only whether one exists.
| Array | Start | Result | Reasoning |
|---|---|---|---|
| [2, 3, 0, 1, 4] | 4 | true | From 4 the value is 4, so jump to 0. Index 0 holds 2, so jump to 2, which holds 0. |
| [4, 2, 3, 0, 3, 1, 2] | 0 | true | 0 to 4, then 4 to 1, then 1 to 3, where the value is 0. |
| [3, 0, 2, 1, 2] | 2 | false | A zero exists at index 1, but from 2 you only ever visit 0, 2, 3 and 4. |
| [0] | 0 | true | You already stand on a zero. |
The third row is the one to show an interviewer. It proves the answer is not simply whether the array contains a zero. Reachability is the whole question.
Questions worth asking before you code: can values be zero at the start index (yes, and then the answer is immediately true), can the array be huge (it usually can, so recursion depth matters in Python), and are values bounded by the length or can a jump overshoot by a lot (overshooting is simply out of bounds and ignored).
Spot the graph
Most Jump Game variants hide a graph, and this one hides it barely at all. Each index is a vertex. Each vertex has up to two directed edges, one to the right and one to the left. Asking whether a zero is reachable from the start is a plain reachability query, and the standard tool for reachability is a traversal that remembers where it has been. Once you say the word graph out loud, the rest of the interview is about doing that traversal cleanly.
Unlike the first Jump Game, a greedy sweep from left to right does not work here, because moves go in both directions. An index on the far right can send you back to the far left. That is why the search needs a visited set rather than a single running maximum.
A slow but correct first answer
If the graph idea does not come straight away, there is a correct answer that needs no recursion. Keep a boolean per index saying whether it is known to be reachable. Start with only the start index marked. Then sweep the whole array: for every marked index, mark its two targets. Repeat sweeps until one pass changes nothing. At that point the marked set is exactly the reachable set, and you check whether any marked index holds a zero.
def reaches_zero_slow(hops, start):
n = len(hops)
known = [False] * n
known[start] = True
changed = True
while changed:
changed = False
for i in range(n):
if not known[i]:
continue
for j in (i + hops[i], i - hops[i]):
if 0 <= j < n and not known[j]:
known[j] = True
changed = True
return any(known[i] and hops[i] == 0 for i in range(n))Each sweep costs O(n), and in the worst case a sweep discovers only one new index, for example when the chain of jumps keeps pointing leftward against the scan order. That gives O(n²) time. It is a fine thing to say first, and it doubles as the brute-force checker for testing the faster version.
The main approach: search with a visited array
Instead of sweeping blindly, only look at indexes you have just discovered. Push the start onto a stack. Pop an index; if it is out of bounds or already visited, skip it. If its value is 0, you are done. Otherwise mark it visited and push both of its targets. When the stack empties without finding a zero, the answer is false.
Two small choices keep the code short. Checking bounds when you pop, rather than before you push, means one guard covers both directions. And checking the zero before marking visited is harmless, because a zero index has no useful moves anyway: both of its targets are itself.
def reaches_zero(hops, start):
n = len(hops)
visited = [False] * n
todo = [start]
while todo:
i = todo.pop()
if i < 0 or i >= n or visited[i]:
continue
if hops[i] == 0:
return True
visited[i] = True
todo.append(i + hops[i])
todo.append(i - hops[i])
return Falsefunction reachesZero(hops, start) {
const n = hops.length;
const visited = new Array(n).fill(false);
const todo = [start];
while (todo.length > 0) {
const i = todo.pop();
if (i < 0 || i >= n || visited[i]) continue;
if (hops[i] === 0) return true;
visited[i] = true;
todo.push(i + hops[i], i - hops[i]);
}
return false;
}Swapping the stack for a queue turns this into breadth-first search with the same result and the same bounds. Breadth-first would also tell you the fewest moves to a zero, which is a natural follow-up question. A recursive version reads nicely too, but in Python a long chain of jumps can exceed the default recursion limit, so the explicit stack is the safer choice to write on a whiteboard.
Trace on the second example
Array [4, 2, 3, 0, 3, 1, 2], start 0. Pop 0: value 4, push 4 and -4. Pop -4: out of bounds. Pop 4: value 3, push 7 and 1. Pop 1: value 2, push 3 and -1. Pop -1: skipped. Pop 3: value 0, return true. Four real indexes were touched out of seven.
Complexity
| Version | Time | Extra memory | Comment |
|---|---|---|---|
| Repeated sweeps | O(n²) worst case | O(n) | Simple to reason about; good as a test oracle |
| Stack-based DFS | O(n) | O(n) for visited and the stack | The expected answer |
| Queue-based BFS | O(n) | O(n) | Same bound; also yields the shortest number of moves |
Every index is marked visited at most once and pushes at most two entries, so the stack sees at most 2n + 1 pushes in total. If the interviewer allows mutating the input, you can mark a visited index by negating its value and drop the separate array, which brings extra space down to the stack alone. Say that you are changing the caller's data before you do it.
Edge cases
- The start index already holds 0: return true without moving.
- A one-element array: either it is [0] and the answer is true, or it is not and the only moves leave the array.
- No zero anywhere in the array: the search drains and returns false. You could check this up front as a shortcut.
- A zero that exists but is unreachable, as in [3, 0, 2, 1, 2] from index 2.
- Two indexes that point at each other, such as values that bounce between positions 1 and 3. Only the visited check stops an infinite loop.
- Very large values: a jump far past either end is just out of bounds, not an error.
Common mistakes
- No visited tracking. Recursion without memory loops forever on the first cycle.
- Marking visited only on push but checking bounds late. Mixing the two orders can index past the end of the visited array. Pick one place for the bounds check.
- Answering whether a zero exists. That ignores reachability and fails on the third example.
- Trying a left-to-right greedy. It works for the first Jump Game because moves only go forward; here they do not.
- Deep recursion in Python. A path of tens of thousands of jumps can hit the recursion limit; an explicit stack avoids it.
Explaining it in an interview
Fictional example
- Candidate
- Each index has at most two moves, so I will treat the array as a graph and ask whether any zero-valued vertex is reachable from the start.
- Candidate
- Moves go both ways, so a greedy reach pointer will not work, and the graph can have cycles. I need a visited array.
- Candidate
- I will use an explicit stack: pop, skip if out of range or seen, return true on a zero, else mark and push both targets. Linear time and space.
- Interviewer
- What if I want the fewest jumps?
- Candidate
- Switch the stack to a queue and store a distance with each index. The first zero dequeued is the closest.
Where to go next in this set
Jump Game VII keeps the reachability question but limits moves to a window ahead of you, which rewards a sliding count instead of a search. Minimum Jumps to Reach Home turns the same breadth-first idea into a shortest-path problem with an extra rule about consecutive moves. For the underlying traversal patterns, see algorithm interview questions.
Rehearse it with Natively
When you practice on your own, Natively can read a problem like this from a screenshot and sketch an approach in its overlay, which is handy for checking your graph framing after you have committed to one. Run a mock round with a friend and its transcript shows whether you mentioned cycles and the visited array before writing code. More on an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Jump Game III?
Treat each index as a graph node with edges to i + a[i] and i - a[i]. Run DFS or BFS from the start with a visited array and return true as soon as you reach an index holding 0.
What is the time complexity of Jump Game III?
O(n) time and O(n) extra space, because each index is visited at most once and pushes at most two neighbors.
Why does a greedy approach fail for Jump Game III?
Moves go both left and right, so a single furthest-reach pointer cannot describe what is reachable. You need a search that remembers visited indexes.
Should Jump Game III use DFS or BFS?
Either works for the yes or no answer with the same bounds. BFS is the better pick if the follow-up asks for the fewest jumps to a zero.
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.
