All Paths From Source to Target - Problem

Given a directed acyclic graph (DAG) with n nodes labeled from 0 to n-1, find all possible paths from the source node 0 to the target node n-1.

The graph is represented as an adjacency list where graph[i] contains all nodes you can reach directly from node i. Since this is a DAG, there are no cycles, which guarantees that our path-finding will eventually terminate.

Goal: Return all possible paths from node 0 to node n-1 in any order.

Example: If we have a graph [[1,2],[3],[3],[]], this represents:
- Node 0 can go to nodes 1 and 2
- Node 1 can go to node 3
- Node 2 can go to node 3
- Node 3 has no outgoing edges (target)

Input & Output

example_1.py β€” Basic Graph
$ Input: graph = [[1,2],[3],[3],[]]
β€Ί Output: [[0,1,3],[0,2,3]]
πŸ’‘ Note: There are two paths from node 0 to node 3: 0->1->3 and 0->2->3. Both paths are valid since we can reach the target node 3 from source node 0.
example_2.py β€” Linear Path
$ Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
β€Ί Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
πŸ’‘ Note: There are 5 different paths from node 0 to node 4. Each represents a different route through the directed graph.
example_3.py β€” Single Path
$ Input: graph = [[1],[2],[]]
β€Ί Output: [[0,1,2]]
πŸ’‘ Note: Only one path exists from node 0 to node 2: 0->1->2. This is a simple linear graph with no alternative routes.

Visualization

Tap to expand
0START123TARGETPath 1: [0,1,3]Path 2: [0,2,3]All Paths from Source to TargetDFS explores each possible route systematically:β€’ Try route through node 1 β†’ find path [0,1,3]β€’ Backtrack and try route through node 2 β†’ find path [0,2,3]
Understanding the Visualization
1
Initialize
Start at source node 0 with empty path
2
Explore
Add current node to path and explore each neighbor
3
Found Target
When reaching target node, save current path to results
4
Backtrack
Remove current node and try other branches
Key Takeaway
🎯 Key Insight: DFS with backtracking naturally explores all paths in a tree-like manner, and the DAG property ensures termination without cycles.

Time & Space Complexity

Time Complexity
⏱️
O(2^N * N)

In worst case, we might have 2^N paths (exponential), and each path can be up to N nodes long

n
2n
βœ“ Linear Growth
Space Complexity
O(2^N * N)

Space for storing all paths, plus recursion stack depth of at most N

n
2n
βœ“ Linear Space

Constraints

  • n == graph.length
  • 2 ≀ n ≀ 15
  • 0 ≀ graph[i][j] < n
  • graph[i][j] != i (i.e., there will be no self-loops)
  • All the elements of graph[i] are unique
  • The input graph is guaranteed to be a DAG
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28 Apple 22
68.0K Views
Medium Frequency
~15 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen