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:

  1. Record a vertex the first time it is visited, and visit each reachable vertex at most once.
  2. When expanding u, inspect graph[u] from left to right, exploring the entire unvisited subgraph reachable from the first unvisited neighbor before moving on to later neighbors in graph[u].
  3. Directed cycles, self-loops, and repeated parallel edges may occur and must terminate without revisiting vertices.
  4. Ignore vertices that cannot be reached along directed paths from start_node.
  5. Vertices with zero outgoing edges (including start_node itself when graph is empty or omits start_node) might not appear as keys in graph; 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 across graph do not exceed 10^5.
  • The graph may contain cycles, self-loops, duplicate neighbor entries, disconnected components, and sink vertices omitted from graph.keys().

Step-by-step walkthrough

  1. 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 vertex v reachable via a one-way edge u -> v—along with start_node. Our goal is to return all vertices reachable from start_node in 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 ─────► 3
    

    Starting at 5, its neighbors are [2, 8]. We follow the first neighbor 2 before touching 8. From 2, we visit 9. Vertex 9 only loops to itself (9 -> 9) and 2's second neighbor 5 is already visited, so we backtrack to 5 and explore 8 -> 3, producing [5, 2, 9, 8, 3].

    Three rules from the specification guide our design:

    • Cycles and self-loops can exist (5 <-> 2 and 9 -> 9), so we record visited vertices in a hash set to 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 via graph.get(node, []).
    • Isolated start_node (or empty graph): when start_node is absent from graph's keys (like "R" in Example 3), it simply has [] outgoing edges, so DFS visits start_node and returns [start_node].
  2. 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_order
    

    This 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 1000 by default (sys.getrecursionlimit()), so a long chain 0 -> 1 -> 2 -> ... -> 2000 raises RecursionError. Using our own Python list as an explicit stack removes that depth limit completely.

  3. Replace the call stack with an explicit stack

    A Python list acts 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:

    1. Push neighbors in reverse (reversed(neighbors)). Because a stack pops its newest element first, pushing [2, 8] as 8 then 2 places 2 on top so 2 is explored while 8 waits underneath.
    2. Mark a vertex visited when you POP it, not when you push it. Look at Example 2 (graph = {'S': ['M', 'T'], 'M': ['T', 'K']}, start_node = 'S'). True DFS goes S -> 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 in O(1) time when popped later.

  4. 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_order
    

    Notice that we check visited in two places for two distinct reasons:

    • if current_node in visited: continue after stack.pop() is required for correctness, because an unvisited vertex can be pushed onto stack by multiple predecessors before any copy is popped.
    • if neighbor not in visited: before stack.append(neighbor) is a helpful filter that skips pushing vertices already visited earlier (such as 2 -> 5 or 9 -> 9).
  5. Trace Example 1 step by step

    Let's trace graph = {5: [2, 8], 2: [9, 5], 8: [3], 9: [9], 3: []} with start_node = 5 (the right end of stack is 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 stack becomes empty, we return [5, 2, 9, 8, 3], matching Example 1.

  6. 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):

  1. Start with stack = ['S']. Pop 'S', mark it visited (traversal_order = ['S']), and push its neighbors in reverse: 'T' then 'M', giving stack = ['T', 'M'].
  2. Pop 'M', mark it visited (traversal_order = ['S', 'M']), and push its unvisited neighbors in reverse: 'K' then 'T', giving stack = ['T', 'K', 'T'].
  3. 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']).
  4. Finally pop the older 'T' at the bottom of stack, see 'T' is already in visited, 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 visited check 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 visited and traversal_order hold V vertices while stack can 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 {} or start_node absent from graph's keys: graph.get(start_node, []) returns [], so the function visits start_node once and returns [start_node] (as in Example 3).
  • Self-loops (9: [9]): 9 is added to visited before its neighbors are scanned, so 9 is never pushed back onto stack.
  • Sink vertices appearing only inside neighbor lists: graph.get(current_node, []) defaults to [] instead of raising KeyError.
  • Parallel / duplicate edges ('S': ['M', 'M']): 'M' is pushed twice; the first pop visits 'M' and the second pop hits if 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 in traversal_order.
  • Deep linear chains (thousands of vertices): our explicit list stack lives on the heap and scales to hundreds of thousands of vertices without hitting Python's recursion limit.

Common mistakes

  • Marking vertices visited when 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 explores 8 before 2, reversing sibling order at every vertex.
  • Indexing graph[current_node] directly: crashes with KeyError whenever a reachable vertex has zero outgoing edges and was omitted from graph's keys.
  • Popping from the front (stack.pop(0) or deque.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 visited set cannot distinguish a cycle from two separate paths converging at an already-finished diamond vertex (S -> M -> T and S -> T). Instead, track three states per vertex—UNSEEN (0), ACTIVE (1), and DONE (2)—and report a cycle only when an outgoing edge points to an ACTIVE vertex, 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 pushing node's neighbors so node transitions from ACTIVE to DONE once 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 visited and traversal_order store V vertices while duplicate pending entries on stack are 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 visited set across the entire run and iterate through every vertex key in graph, 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 over graph.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 outside graph, accept an explicit vertices collection as well).

Follow-up questions

Similar questions

More Cadence interview questions

All 2 Cadence questions →