Bird
Raised Fist0

Consider the following iterative DFS code to find all paths from source (0) to target in a DAG:

easy🧾 Code Trace Q12 of Q15
Topological Sort - All Paths From Source to Target (DAG)
Consider the following iterative DFS code to find all paths from source (0) to target in a DAG:
from typing import List

def allPathsSourceTarget(graph: List[List[int]]) -> List[List[int]]:
    target = len(graph) - 1
    res = []
    stack = [(0, [0])]

    while stack:
        node, path = stack.pop()
        if node == target:
            res.append(path)
        else:
            for nei in graph[node]:
                stack.append((nei, path + [nei]))
    return res

# Input graph: [[1,2],[3],[3],[]]
print(allPathsSourceTarget([[1,2],[3],[3],[]]))
What is the exact output of this code?
A[[0,1,3],[0,2,3]]
B[[0,1,3]]
C[[0,2,3],[0,1,3]]
D[[0,1,2,3]]
Step-by-Step Solution
  1. Step 1: Trace stack operations

    Initial stack: [(0,[0])]. Pop (0,[0]), neighbors 1 and 2 pushed: stack=[(1,[0,1]),(2,[0,2])]. Next pop (2,[0,2]), neighbor 3 pushed: stack=[(1,[0,1]),(3,[0,2,3])]. Pop (3,[0,2,3]) -> target reached, add path.
  2. Step 2: Continue tracing remaining stack

    Pop (1,[0,1]), neighbor 3 pushed: stack=[(3,[0,1,3])]. Pop (3,[0,1,3]) -> target reached, add path. Result order: [[0,2,3],[0,1,3]].
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Stack is LIFO, so last neighbor pushed is processed first [OK]
Quick Trick: Stack pops last pushed neighbor first, reversing neighbor order [OK]
Common Mistakes:
MISTAKES
  • Assuming neighbors processed in original order
  • Confusing BFS order with DFS stack order
Trap Explanation:
PITFALL
  • Candidates often expect neighbors processed in order, but stack reverses it causing reversed path order.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to mentally execute iterative DFS with stack and path tracking.
Master "All Paths From Source to Target (DAG)" in Topological Sort

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Topological Sort Quizzes