All Paths From Source to Target solution explained
All Paths From Source to Target is a backtracking problem: run a depth-first search from node 0 with one shared path list, append a node before exploring it and pop it afterward, and save a copy of the path whenever you reach node n - 1. Because the graph is acyclic, no visited set is needed. The output itself can hold about 2ⁿ paths, so O(2ⁿ · n) time is the true bound for any correct method.
By Evin JohnPublished 7 min read
The problem in plain words
You get a list called graph with n entries. Entry i lists the nodes you can move to directly from node i. Edges only go one way, and there are no cycles, so you can never come back to a node you already passed. The start is node 0 and the finish is node n - 1. Return a list of all distinct routes from start to finish, each written as the sequence of nodes it visits. The routes can come in any order.
| graph | Routes from 0 to the last node | Note |
|---|---|---|
| [[1,2], [3], [3], []] | [0,1,3], [0,2,3] | Two branches that meet again. |
| [[1], []] | [0,1] | The smallest interesting case. |
| [[1,2,3], [2], [3], []] | [0,1,2,3], [0,2,3], [0,3] | A shortcut straight to the end is its own route. |
| [[], [2], []] | none | Node 0 has no outgoing edges, so the finish is unreachable. |
| [[1,2], [], [3], []] | [0,2,3] | Node 1 is a dead end and contributes nothing. |
Questions to ask before coding: is the graph guaranteed to be acyclic? If not, you need a visited set on the current path, and the problem becomes different. How large can n get? Small limits are a hint that exponential output is expected. And is node n - 1 allowed to have outgoing edges? It usually has none, but your code should stop at it either way.
Why it appears in interviews
It is the cleanest example of backtracking on a graph, with no pruning rules to distract from the mechanics. The interviewer watches three habits: whether you add and remove from the path symmetrically, whether you copy the path when saving it instead of saving a reference that later changes, and whether you can state the complexity honestly. Saying "O(V + E)" here is a red flag, because the answer alone can be exponential in size.
Slow approach: BFS with full path copies
Put the one-node path [0] in a queue. Pop a path, look at its last node, and for each neighbor push a new list that is the old path plus that neighbor. When a popped path ends at n - 1, add it to the answer. This is correct and easy to explain, but every step allocates a brand new list, and the queue holds every partial route at the same time. On a dense DAG that is a lot of memory spent on routes that are not finished yet.
from collections import deque
def all_routes_bfs(graph):
finish = len(graph) - 1
routes = []
queue = deque([[0]])
while queue:
route = queue.popleft()
last = route[-1]
if last == finish:
routes.append(route)
continue
for nxt in graph[last]:
queue.append(route + [nxt])
return routesMain approach: DFS with one shared path
Depth-first search explores one route at a time, so a single list can represent the current route. Before visiting a neighbor, append it. After the visit returns, pop it, which restores the list to what it was. When the current node is n - 1, save a copy of the list. Copies happen only for finished routes, and the working memory is just the path and the call stack, both at most n long.
def all_routes(graph):
finish = len(graph) - 1
routes = []
route = [0]
def explore(node):
if node == finish:
routes.append(route.copy())
return
for nxt in graph[node]:
route.append(nxt)
explore(nxt)
route.pop()
explore(0)
return routesfunction allRoutes(graph) {
const finish = graph.length - 1;
const routes = [];
const route = [0];
function explore(node) {
if (node === finish) {
routes.push(route.slice());
return;
}
for (const nxt of graph[node]) {
route.push(nxt);
explore(nxt);
route.pop();
}
}
explore(0);
return routes;
}No visited set appears anywhere, and that is deliberate. In a DAG you cannot loop, and the same node is supposed to appear in many different routes. Adding a global visited set would wrongly block the second route through a shared node.
Optional pruning for dead ends
If many branches never reach the finish, precompute which nodes can reach n - 1, for example with a memoized check or a reverse BFS from the finish, and skip neighbors that cannot. Output size is unchanged, but wasted exploration drops. Mention it as an improvement; most interviewers do not require it.
Memoized route lists
Another clean version defines routes_from(v) as the list of routes from v to the finish, with each one formed by putting v in front of a route from a neighbor. Caching routes_from shares work across branches. It is a nice talking point about dynamic programming, but because the routes still have to be materialized, the worst case remains O(2ⁿ · n).
Tracing [[1,2,3], [2], [3], []]
- Startroute = [0]. Try neighbor 1: route = [0,1].
- Go deeperFrom 1, try 2: route = [0,1,2]. From 2, try 3: route = [0,1,2,3]. That is the finish, so save a copy.
- BacktrackPop back to [0]. Try neighbor 2: route = [0,2], then [0,2,3]. Save it.
- Last branchPop back to [0]. Try 3: [0,3] is complete. Save it. Three routes in total.
Complexity
Consider the densest DAG, where every node i has an edge to every node j greater than i. Any subset of the middle nodes 1 to n - 2, taken in increasing order, forms a valid route, so there are 2ⁿ⁻² routes. Each can be up to n nodes long, so just writing the output costs O(2ⁿ · n).
| Approach | Time | Working memory beyond the output |
|---|---|---|
| BFS with path copies | O(2ⁿ · n) worst case | Every partial route at once |
| DFS backtracking | O(2ⁿ · n) worst case, about P · L in practice | O(n) for the path and the stack |
| DFS with dead-end pruning | Same worst case, less wasted work | O(n) plus an O(n) reach table |
Edge cases to test
- The finish is unreachable: return an empty list.
- A direct edge from 0 to n - 1 alongside longer routes.
- Dead-end branches that never reach the finish.
- Nodes that appear in many routes, which catches an accidental global visited set.
- A single node graph, if the constraints allow it: the start is the finish, so the one route is [0].
Mistakes that cost points
- Saving
routeitself instead of a copy. Every saved entry then points at the same list, which ends up as [0] after all the pops. - Forgetting the pop after the recursive call, so later routes include nodes from earlier branches.
- Adding a global visited set out of habit, which drops valid routes.
- Stating O(V + E) time.
- Starting the path empty and appending 0 inside the loop, which duplicates or skips the start depending on the details.
How it might sound in the interview
Fictional example
- Candidate
- The graph has no cycles, so a depth-first walk never loops and I do not need a visited set. I will keep one route list, append before going deeper, pop on the way back, and copy the list when I hit the last node.
- Candidate
- The complexity is bounded by the output. A fully connected DAG has two to the n minus two routes, each up to n long, so the worst case is about 2ⁿ times n.
- Candidate
- If you expect many dead ends, I can precompute which nodes reach the finish and skip the rest, which does not change the worst case but saves work in practice.
Continue the set
Course Schedule IV asks only whether a route exists between two nodes, so it can precompute instead of listing. Reorder Routes to Make All Paths Lead to the City Zero moves to a tree and counts edges that point the wrong way. The algorithm interview questions page covers backtracking more broadly.
Practice with Natively
When you drill backtracking, Natively can read a graph problem from a screenshot and suggest the shape of a solution, a useful check once you have your own version on paper. Since it transcribes your practice session on your computer, you can listen back for whether you justified skipping the visited set and gave an honest complexity. Read about the best AI tools for coding interviews.
Questions people ask
How do you solve All Paths From Source to Target?
Run a depth-first search from node 0 with one shared path list. Append each neighbor before exploring it, pop it afterward, and save a copy of the path whenever you reach node n - 1.
Why is there no visited set in the solution?
The graph is acyclic, so a walk can never loop, and the same node is meant to appear in many different paths. A global visited set would wrongly drop valid paths.
What is the time complexity of All Paths From Source to Target?
It is bounded by the output. A fully connected DAG has 2^(n-2) paths of up to n nodes each, so the worst case is O(2^n · n) for any correct method.
Should I use BFS or DFS for this problem?
Both are correct. DFS with backtracking is preferred because it keeps one working path and copies only finished paths, while BFS stores every partial path at once.
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.
