All Paths From Source to Target (LeetCode 797): Solution and Explanation

Medium
Backtracking
Depth First Search
Breadth First Search
Graph

Given a directed acyclic graph as an adjacency list, list every path that starts at node 0 and ends at the last node, n - 1. The paths may be returned in any order.

Intuition

The problem asks for every path, not the shortest or the count, so the work is enumeration. Backtracking is the natural tool: walk forward one edge at a time and undo the step when you come back.

Keep one list, the current path. From its last node, try each outgoing edge: append the neighbour, explore from there, then pop it so the next edge starts from the same prefix.

Usually a graph DFS needs a visited set to avoid loops. A DAG has no cycles, so no walk can come back to a node already on the path, and every walk from 0 that reaches n - 1 is a distinct valid path.

Approach: DFS with backtracking

  1. Set target = n - 1 and start with path = [0].
  2. In dfs(node): if node == target, append a copy of path to the answer and return.
  3. Otherwise, for each nxt in graph[node]: append nxt to path, call dfs(nxt), then pop nxt.
  4. Call dfs(0) and return the collected paths.

Step-by-step example

graph = [[1,2],[3],[3],[]]
  1. Start at 0 with path [0]. Its first edge goes to 1, so the path becomes [0,1].
  2. Node 1 has one edge, to 3. The path becomes [0,1,3] and 3 is the target, so [0,1,3] is saved.
  3. Pop 3 and then 1, which brings the path back to [0]. Node 0's second edge goes to 2: path [0,2].
  4. From 2 the edge to 3 gives [0,2,3], which is saved. Everything is popped and the answer is [[0,1,3],[0,2,3]].

Code: Python, Java, C++

1class Solution:
2    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
3        target = len(graph) - 1
4        paths, path = [], [0]
5
6        def dfs(node):
7            if node == target:
8                paths.append(path[:])
9                return
10            for nxt in graph[node]:
11                path.append(nxt)
12                dfs(nxt)
13                path.pop()
14
15        dfs(0)
16        return paths
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(2^n * n)

A DAG on n nodes can have up to 2^(n-2) paths from 0 to n - 1 (when every node links to every later node), and copying each path costs O(n).

Space

O(n)

The recursion depth and the current path are at most n, not counting the output itself.

Other approaches

BFS over partial paths (time O(2^n * n), space O(2^n * n))

Put [0] in a queue. Pop a path, and for each neighbour of its last node push a new path with the neighbour appended; paths ending at n - 1 go to the answer. Same output, but every partial path is a separate copy in memory.

Memoized paths from each node (time O(2^n * n), space O(2^n * n))

Compute allPaths(u) = for each neighbour v, [u] + every path in allPaths(v), caching the result for each node. Shared suffixes are computed once, though building the final lists still costs the size of the output.

Common mistakes

  • Appending path itself instead of a copy. Every saved entry then points to the same list, which ends up empty after backtracking.
  • Forgetting to pop after the recursive call, so later branches start from a wrong prefix.
  • Adding a visited set. It is unnecessary in a DAG and wrong if it is never cleared, because two different paths may pass through the same node.
  • Assuming node n - 1 has no outgoing edges and skipping the target check. Check for the target before exploring further.

Frequently asked questions

Why is there no visited set?

The graph is acyclic, so a DFS can never return to a node on its current path. Different paths may share nodes, and marking nodes as visited globally would wrongly cut those paths off.

Does the order of the output matter?

No. Any order of the paths is accepted. Each path itself must list nodes in order from 0 to n - 1.

Can the answer be empty?

Yes. If no sequence of edges leads from 0 to n - 1, there are no paths and the answer is an empty list.

Why is the worst case exponential?

When every node has an edge to every later node, each of the n - 2 middle nodes can be in or out of a path, giving 2^(n-2) paths. With n at most 15 that is only 8192 paths.