Depth-First Graph Traversal
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Given a directed graph encoded as a dictionary graph and a starting vertex start_node, implement dfs_traversal(graph, start_node) to return the sequence of vertices discovered by a depth-first search (DFS) beginning at start_node.
For each key u in graph, graph[u] is an ordered list of destination vertices v corresponding to outgoing directed edges u -> v. Follow standard pre-order depth-first exploration:
- Record a vertex the first time it is visited, and visit each reachable vertex at most once.
- When expanding
u, inspectgraph[u]from left to right, exploring the entire unvisited subgraph reachable from the first unvisited neighbor before moving on to later neighbors ingraph[u]. - Directed cycles, self-loops, and repeated parallel edges may occur and must terminate without revisiting vertices.
- Ignore vertices that cannot be reached along directed paths from
start_node. - Vertices with zero outgoing edges (including
start_nodeitself whengraphis empty or omitsstart_node) might not appear as keys ingraph; treat any absent key as having an empty neighbor list[].
Examples
Example 1
Input:
graph = {5: [2, 8], 2: [9, 5], 8: [3], 9: [9], 3: []}
start_node = 5
Output:
[5, 2, 9, 8, 3]
Explanation:
Starting at 5, DFS follows its first neighbor 2 before 8. From 2, it visits 9 (skipping the self-loop 9 -> 9 and the cycle edge 2 -> 5 back to already-visited 5), then backtracks to 5 to explore 8 and finally 3.
Example 2
Input:
graph = {"S": ["M", "T"], "M": ["T", "K"], "X": ["S"]}
start_node = "S"
Output:
["S", "M", "T", "K"]
Explanation:
From "S", DFS enters "M" first. "M" visits "T" (an omitted sink key) and then "K" (also an omitted sink key). Returning to "S", neighbor "T" is already visited. Vertex "X" has no incoming path from "S" and is excluded.
Example 3
Input:
graph = {"P": ["Q"], "Q": ["P"]}
start_node = "R"
Output:
["R"]
Explanation:
"R" is absent from graph's keys, so it has zero outgoing edges; DFS visits "R" and finishes immediately.
Constraints
- Vertex labels are hashable values such as integers or strings.
0 <= len(graph) <= 10^5, and total directed edges acrossgraphdo not exceed10^5.- The graph may contain cycles, self-loops, duplicate neighbor entries, disconnected components, and sink vertices omitted from
graph.keys().
Step-by-step walkthrough
Understand the graph and depth-first order
We are given a directed graph stored as an adjacency list—a dictionary where
graph[u]lists every vertexvreachable via a one-way edgeu -> v—along withstart_node. Our goal is to return all vertices reachable fromstart_nodein the exact order a depth-first search (DFS) first encounters them, visiting each vertex once."Depth-first" means we plunge as far as possible down the first unvisited neighbor's branch before returning to inspect later neighbors. Look at Example 1 (
start_node = 5):graph = {5: [2, 8], 2: [9, 5], 8: [3], 9: [9], 3: []} 5 ◄────► 2 ─────► 9 ──┐ │ ▲ │ ▼ └───┘ 8 ─────► 3Starting at
5, its neighbors are[2, 8]. We follow the first neighbor2before touching8. From2, we visit9. Vertex9only loops to itself (9 -> 9) and2's second neighbor5is already visited, so we backtrack to5and explore8 -> 3, producing[5, 2, 9, 8, 3].Three rules from the specification guide our design:
- Cycles and self-loops can exist (
5 <-> 2and9 -> 9), so we record visited vertices in a hashsetto prevent infinite loops. - Sink vertices may be omitted from
graph's keys: if a vertex has zero outgoing edges (like"T"and"K"in Example 2), we look up neighbors safely viagraph.get(node, []). - Isolated
start_node(or emptygraph): whenstart_nodeis absent fromgraph's keys (like"R"in Example 3), it simply has[]outgoing edges, so DFS visitsstart_nodeand returns[start_node].
- Cycles and self-loops can exist (
Start with textbook recursion and see its depth limit
The cleanest way to define DFS order is a small recursive helper: mark the current vertex visited, append it to the output, and recurse on each unvisited neighbor from left to right:
def dfs_recursive(graph, start_node): traversal_order = [] visited = set() def visit(node): visited.add(node) traversal_order.append(node) for neighbor in graph.get(node, []): if neighbor not in visited: visit(neighbor) visit(start_node) return traversal_orderThis recursive function visits every reachable vertex and edge once. However, every step deeper along a chain adds another frame onto Python's call stack. CPython caps call depth at
1000by default (sys.getrecursionlimit()), so a long chain0 -> 1 -> 2 -> ... -> 2000raisesRecursionError. Using our own Pythonlistas an explicit stack removes that depth limit completely.Replace the call stack with an explicit stack
A Python
listacts as a last-in, first-out (LIFO) stack via.append()(push) and.pop()(pop from the right end). Two details ensure our iterative loop visits vertices in the exact same order as recursion:- Push neighbors in reverse (
reversed(neighbors)). Because a stack pops its newest element first, pushing[2, 8]as8then2places2on top so2is explored while8waits underneath. - Mark a vertex
visitedwhen you POP it, not when you push it. Look at Example 2 (graph = {'S': ['M', 'T'], 'M': ['T', 'K']},start_node = 'S'). True DFS goesS -> M -> T -> K. Compare marking on push versus marking on pop:
Graph: S -> [M, T], M -> [T, K] WRONG (mark visited on push): pop S -> push T, M and mark {S, M, T} visited pop M -> T is already marked visited! M only pushes K order: [S, M, K, T] <-- WRONG: M skipped T before visiting it! RIGHT (mark visited on pop): start: stack = [S] pop S -> visit S, push T then M -> stack = [T, M] pop M -> visit M, push K then T -> stack = [T, K, T] pop T -> visit T -> stack = [T, K] pop K -> visit K -> stack = [T] pop T -> already in visited, skip -> stack = [] order: [S, M, T, K] <-- MATCHES recursive DFS!Allowing
'T'to sit on the stack twice is completely safe: the deeper copy on top gets visited at the right moment, and the older copy underneath is skipped inO(1)time when popped later.- Push neighbors in reverse (
Write the iterative DFS function
Putting those pieces together gives a compact loop:
def dfs_traversal(graph: Dict[object, List[object]], start_node: object) -> List[object]: # traversal_order: nodes in the exact order DFS first visits them, e.g. [5, 2, 9, 8, 3]. traversal_order: List[object] = [] # visited: hash set of already-visited nodes so cycles and self-loops terminate. visited: Set[object] = set() # stack: LIFO stack of candidate nodes to explore next; the right end is the top. stack: List[object] = [start_node] while stack: current_node = stack.pop() # A node may be pushed multiple times via different incoming edges before its # first visit; marking on pop (and skipping duplicates) preserves true DFS order. if current_node in visited: continue visited.add(current_node) traversal_order.append(current_node) # Nodes with no outgoing edges may be omitted as dictionary keys. neighbors = graph.get(current_node, []) # Push neighbors in reverse so the first listed neighbor sits on top of the stack # and gets explored first, matching standard recursive DFS order. for neighbor in reversed(neighbors): if neighbor not in visited: stack.append(neighbor) return traversal_orderNotice that we check
visitedin two places for two distinct reasons:if current_node in visited: continueafterstack.pop()is required for correctness, because an unvisited vertex can be pushed ontostackby multiple predecessors before any copy is popped.if neighbor not in visited:beforestack.append(neighbor)is a helpful filter that skips pushing vertices already visited earlier (such as2 -> 5or9 -> 9).
Trace Example 1 step by step
Let's trace
graph = {5: [2, 8], 2: [9, 5], 8: [3], 9: [9], 3: []}withstart_node = 5(the right end ofstackis the top):Step stack before pop in visited? traversal_order pushed (reversed) stack after ──── ──────────── ─── ─────────── ──────────────── ────────────────── ─────────── 1 [5] 5 no [5] 8, then 2 [8, 2] 2 [8, 2] 2 no [5, 2] (skip 5), push 9 [8, 9] 3 [8, 9] 9 no [5, 2, 9] (skip 9) [8] 4 [8] 8 no [5, 2, 9, 8] push 3 [3] 5 [3] 3 no [5, 2, 9, 8, 3] (none) []Once
stackbecomes empty, we return[5, 2, 9, 8, 3], matching Example 1.Full solution
from typing import Any, Dict, List, Optional, Set, Tuple def dfs_traversal(graph: Dict[object, List[object]], start_node: object) -> List[object]: # traversal_order: nodes in the exact order DFS first visits them, e.g. [5, 2, 9, 8, 3]. traversal_order: List[object] = [] # visited: hash set of already-visited nodes so cycles and self-loops terminate. visited: Set[object] = set() # stack: LIFO stack of candidate nodes to explore next; the right end is the top. stack: List[object] = [start_node] while stack: current_node = stack.pop() # A node may be pushed multiple times via different incoming edges before its # first visit; marking on pop (and skipping duplicates) preserves true DFS order. if current_node in visited: continue visited.add(current_node) traversal_order.append(current_node) # Nodes with no outgoing edges may be omitted as dictionary keys. neighbors = graph.get(current_node, []) # Push neighbors in reverse so the first listed neighbor sits on top of the stack # and gets explored first, matching standard recursive DFS order. for neighbor in reversed(neighbors): if neighbor not in visited: stack.append(neighbor) return traversal_order✅ Submit now — all tests should pass.
Intuition & how it works
Imagine exploring a maze of one-way hallways with a piece of chalk and a small notepad. Every time you step into an unchalked room, you draw a chalk mark on the floor (visited set) and write the room's label in your travel log (traversal_order). Before choosing a hallway, you jot down the room's unchalked exits on your notepad from last to first—forming a LIFO (last-in, first-out) stack, a list where the most recently added item is always the next one removed—so the very first exit sits on top of your notepad and you walk straight down that hallway until you reach a dead end or a chalked room, at which point you cross off the top reminder and backtrack.
A naive walk without chalk marks loops forever the first time hallways cycle back like 5 -> 2 -> 5. Writing a recursive helper with a visited set stops infinite loops, yet Python places every active call on its system call stack, which crashes with RecursionError on chains deeper than roughly 1,000 vertices. Worse, if you write an iterative stack loop and mark neighbors visited at the moment you push them onto the stack (the way breadth-first search does), you prevent deeper branches from visiting shared neighbors at the right moment and emit a non-DFS order.
Walk through Example 2 (graph = {'S': ['M', 'T'], 'M': ['T', 'K']} starting from 'S', represented as an adjacency list, a dictionary mapping each vertex to the ordered list of vertices its outgoing edges point to):
- Start with
stack = ['S']. Pop'S', mark it visited (traversal_order = ['S']), and push its neighbors in reverse:'T'then'M', givingstack = ['T', 'M']. - Pop
'M', mark it visited (traversal_order = ['S', 'M']), and push its unvisited neighbors in reverse:'K'then'T', givingstack = ['T', 'K', 'T']. - Pop the top
'T', mark it visited (traversal_order = ['S', 'M', 'T']), and push nothing; next pop'K'and mark it visited (traversal_order = ['S', 'M', 'T', 'K']). - Finally pop the older
'T'at the bottom ofstack, see'T'is already invisited, skip it, and return['S', 'M', 'T', 'K'].
Complexity
- Time: O(V + E), where V is the number of reachable vertices and E is the number of outgoing edges from those vertices. Each reachable vertex passes the
if current_node in visitedcheck once, so its neighbor list is scanned once; across all reachable vertices, those neighbor scans inspect E edges in total, pushing and popping at most E + 1 stack entries with O(1) average hash-set lookups. - Space: O(V + E) in the worst case, because
visitedandtraversal_orderhold V vertices whilestackcan hold up to E + 1 pending entries when many edges point to vertices not yet popped (if strict O(V) stack memory is needed, store(node, iterator_over_neighbors)pairs on the stack instead).
Edge cases
- Empty graph
{}orstart_nodeabsent fromgraph's keys:graph.get(start_node, [])returns[], so the function visitsstart_nodeonce and returns[start_node](as in Example 3). - Self-loops (
9: [9]):9is added tovisitedbefore its neighbors are scanned, so9is never pushed back ontostack. - Sink vertices appearing only inside neighbor lists:
graph.get(current_node, [])defaults to[]instead of raisingKeyError. - Parallel / duplicate edges (
'S': ['M', 'M']):'M'is pushed twice; the first pop visits'M'and the second pop hitsif current_node in visited: continue. - Disconnected components: vertices with no directed path from
start_node(such as'X'in Example 2) are never pushed and never appear intraversal_order. - Deep linear chains (thousands of vertices): our explicit
liststack lives on the heap and scales to hundreds of thousands of vertices without hitting Python's recursion limit.
Common mistakes
- Marking vertices
visitedwhen pushing instead of when popping: visits every vertex once, yet breaks depth-first order whenever a deeper branch reaches an earlier sibling ({'S': ['M', 'T'], 'M': ['T', 'K']}wrongly outputs['S', 'M', 'K', 'T']). - Pushing neighbors left-to-right without
reversed(...): because a stack pops from the right end, pushing[2, 8]left-to-right explores8before2, reversing sibling order at every vertex. - Indexing
graph[current_node]directly: crashes withKeyErrorwhenever a reachable vertex has zero outgoing edges and was omitted fromgraph's keys. - Popping from the front (
stack.pop(0)ordeque.popleft()): turns the stack into a first-in, first-out queue, running breadth-first search (level by level) instead of depth-first search. - Relying on unbounded recursion without noting stack overflow: textbook recursion passes small inputs, so always mention CPython's ~1,000-frame call-stack limit if you write recursion first.
Follow-up questions
- How would you adapt this search to determine whether the directed graph contains a directed cycle? In a directed graph, a single
visitedset cannot distinguish a cycle from two separate paths converging at an already-finished diamond vertex (S -> M -> TandS -> T). Instead, track three states per vertex—UNSEEN(0),ACTIVE(1), andDONE(2)—and report a cycle only when an outgoing edge points to anACTIVEvertex, known as a back edge (an edge leading back to an ancestor currently on the active DFS path). In an iterative implementation, push an exit marker(node, True)onto the stack before pushingnode's neighbors sonodetransitions fromACTIVEtoDONEonce its entire subtree finishes. - How do the runtime and memory usage scale with the count of reachable nodes V and directed edges E? Runtime scales as O(V + E) over the reachable subgraph because each reachable vertex is expanded once and each outgoing edge is inspected once using O(1) average hash-set operations. Worst-case memory is O(V + E) for mark-on-pop iterative DFS since
visitedandtraversal_orderstore V vertices while duplicate pending entries onstackare bounded by E + 1; storing(node, iter(graph.get(node, [])))frames on the stack tightens auxiliary memory to O(V) while keeping O(V + E) time. - How would you extend the function to traverse every node across all disconnected components of the graph? Maintain a single shared
visitedset across the entire run and iterate through every vertex key ingraph, launching the stack loop whenever you encounter an unvisited vertex so the complete DFS forest—the collection of depth-first trees spanning the whole graph—still runs in O(V + E) total time across all vertices and edges. Iterating overgraph.keys()also covers sink vertices that appear only inside neighbor lists because each such sink is reached from its parent key (if completely edgeless isolated vertices exist outsidegraph, accept an explicitverticescollection as well).
Follow-up questions
- How would you adapt this search to determine whether the directed graph contains a directed cycle?
- How do the runtime and memory usage scale with the count of reachable nodes V and directed edges E?
- How would you extend the function to traverse every node across all disconnected components of the graph?
Similar questions
- Positional Encoding in Transformer Models
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One