All Paths From Source to Target
Problem Statement
You are given a directed graph with n nodes, numbered 0 to n − 1. It is given as adjacency lists: graph[i] lists every node that node i has an edge to. The graph has no cycles, so it is a DAG (a directed acyclic graph).
Find every path from node 0 to node n − 1. A path follows the edges one by one. It ends when it reaches node n − 1.
Return all the paths. They can be in any order.
graph, a list of n lists. graph[i] holds the nodes that node i points to.
A list of every path from node 0 to node n − 1. Each path is a list of nodes that starts with 0 and ends with n − 1.
Node 0 points to 1 and 2. Both of them point to 3, which is the target. That gives two paths.
There are five paths. Node 3 is on three of them, so the same node appears in three answers.
Node 0 has no edges, so no path reaches node 1.
- • n is the length of `graph`, with 2 ≤ n ≤ 15.
- • Each number in `graph[i]` is a node from 0 to n − 1.
- • No node has an edge to itself.
- • The numbers inside each list `graph[i]` are unique.
- • The graph has no cycles (it is a DAG).
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Queue whole paths; copy the path for every edge it extends
Push and pop one path while walking; copy it when the target is reached
Start with the path [0] in a queue. Pop a path. If it ends at n − 1, it is an answer. Otherwise, for every edge out of its last node, copy the whole path and add the new node, and push each copy onto the queue. No list is ever shared, so every path is copied again and again.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Backtracking translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.