Skip to contentKEEP THE CRAFTTHE SANCTUARY

Depth-first Search

Finish one reachable branch before returning to another. Give each DFS frame a node and local state, mark graph nodes before descending, and distinguish recursion depth from total graph work.

1 practice exercise17 interview problems

Recognize it when A task needs component reachability, postorder aggregation or branch-local path state.

Checking your account…

Depth-first Search Code Labs

Follow One Branch to Completion

Depth-first search commits to one neighbor path until it ends, then returns to the most recent unfinished choice. A recursive call stack or an explicit stack owns that frontier.

Define the DFS Frame

Each frame needs a node plus the state required below it: parent, depth, path aggregate, or traversal phase. State the return contract before descending so postorder work has a precise meaning.

Trace DFS Frames

Reference
def dfs_frame_trace(adjacency, start):
    if start == -1: return []
    trace = []
    seen = set()
    def visit(node, depth):
        seen.add(node)
        trace.append([node, depth])
        for neighbor in adjacency[node]:
            if neighbor not in seen:
                visit(neighbor, depth + 1)
    visit(start, 0)
    return trace
Practice

Implement dfs_frame_trace(adjacency, start). Return [node, depth] in recursive preorder, preserving neighbor order and visiting each node once. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.

Public tests

  • Carry depth in each frame

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace DFS Frames

def dfs_frame_trace(adjacency, start):
    if start == -1: return []
    trace = []
    seen = set()
    def visit(node, depth):
        seen.add(node)
        trace.append([node, depth])
        for neighbor in adjacency[node]:
            if neighbor not in seen:
                visit(neighbor, depth + 1)
    visit(start, 0)
    return trace

Return to the Parent Before Visiting Its Sibling

The existing DFS Lab follows neighbor order [2,1]. Its first branch contains a cycle back to the root, then it returns to the root before visiting 1. Predict the depth of that final sibling.

Step Executed statement State Why
Root frame seen.add(node) seen={0}, depth=0 Marking precedes all outgoing edges.
Descend through 2 visit(neighbor, depth + 1) node=2, depth=1 The root frame is suspended while its first branch runs.
Reach 3 trace.append([node, depth]) trace ends [3, 2] Depth counts edges in this DFS tree, not shortest graph distance.
Cycle edge if neighbor not in seen: neighbor=0 is already seen The back edge cannot reenter the root.
Root sibling visit(neighbor, depth + 1) node=1, depth=1 Returning restores the root depth 0; the sibling does not inherit depth 2.
Print Output
print(dfs_frame_trace([[2, 1], [], [3], [0]], 0)) [[0, 0], [2, 1], [3, 2], [1, 1]]

Frame depth describes the DFS tree. It need not be the shortest distance in a graph; the BFS page supplies the different frontier proof for that contract.

Mark Before Descending

In a graph, add a node to visited before exploring neighbors. Marking afterward lets a cycle re-enter the same frame. Trees can sometimes use a parent pointer instead, but only when the input is guaranteed acyclic.

Measure a Connected Component

Reference
def component_size(adjacency, start):
    if start == -1: return 0
    seen = set()
    stack = [start]
    while stack:
        node = stack.pop()
        if node in seen: continue
        seen.add(node)
        stack.extend(adjacency[node])
    return len(seen)
Practice

Implement component_size(adjacency, start). Return the number of nodes reachable from start, or 0 for start -1. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.

Public tests

  • Ignore cycles and unreachable nodes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Measure a Connected Component

def component_size(adjacency, start):
    if start == -1: return 0
    seen = set()
    stack = [start]
    while stack:
        node = stack.pop()
        if node in seen: continue
        seen.add(node)
        stack.extend(adjacency[node])
    return len(seen)

Choose Recursive or Iterative DFS

Recursive DFS mirrors the proof and is concise; iterative DFS avoids Python recursion depth and makes traversal phases explicit. Push neighbors in reverse when an explicit stack must reproduce recursive neighbor order. Both take O(V + E).

Explain It in an Interview

Say: “This frame owns one node and this accumulated state. I mark before descending, each edge is considered a bounded number of times, and return means the entire branch is complete.” Include disconnected components, O(depth) recursive frames and O(V) visited storage. The component_size Lab marks on pop, so its explicit stack may retain O(E) pending duplicate entries; it does not inherit the recursive frame-depth bound.

Templates To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Tree DFS with a return value

Ask the children first, then answer for yourself.

The answer for a node can be built from the answers of its left and right subtrees.

Trigger words

  • height
  • diameter
  • balanced tree
  • same tree
  • invert tree
  • path sum
  • every subtree
def max_depth(root):
    if root is None:                  # 1. empty tree
        return 0
    left = max_depth(root.left)       # 2. ask the left child
    right = max_depth(root.right)     # 3. ask the right child
    return 1 + max(left, right)       # 4. combine at this node

Spot it when

  • Height, size, balance, 'same tree'.
  • Any 'for every subtree' question.

Remember

  • Trust the recursive call: assume it returns the right answer for the child.
  • When the best answer may not pass through the root (diameter, max path sum), keep it in an outer variable and update it at every node.

How problems bend it

  • Diameter / maximum path sum: Return the best single branch upward, and update a best variable with left + right at each node.
  • Pass information down: Add a parameter (current max on the path, remaining sum) and update it before recursing.
  • Very deep tree (thousands of levels): Python stops recursion at about 1000 levels. List the nodes parent-before-child with a stack, then walk that list backwards and compute each node from its children's stored answers; the loop body is the recursive body.
  • Two answers per node (take it or skip it): Return a pair from each call: take = node.val + left_skip + right_skip, skip = max(left pair) + max(right pair).
  • Build a tree from traversal orders: Create the node for the current root value, then build its left and right subtrees from the matching ranges; a value -> inorder index dictionary finds the split in O(1).

Graph DFS with a visited set

Build the adjacency list, keep a visited set, explore each unvisited node.

The input is a list of edges (or nodes with neighbors) and you explore connectivity.

Trigger words

  • connected components
  • clone graph
  • valid tree
  • can reach
  • itinerary
  • adjacency list
from collections import defaultdict

def count_components(n, edges):
    graph = defaultdict(list)
    for a, b in edges:
        graph[a].append(b)
        graph[b].append(a)

    visited = set()

    def dfs(node):
        visited.add(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                dfs(neighbor)

    components = 0
    for node in range(n):
        if node not in visited:
            dfs(node)
            components += 1
    return components

Spot it when

  • 'Number of connected components', 'clone a graph', 'can water reach both oceans'.

Remember

  • Add a node to visited before exploring its neighbors.
  • For very deep graphs, the same idea works with an explicit stack instead of recursion.

How problems bend it

  • Clone a graph: Use a dictionary old node -> new node as the visited set.
  • Is it a valid tree?: A tree has exactly n - 1 edges and one connected component.
  • Very deep graph: Replace dfs with a stack: push the start node and mark it visited; pop a node, then mark and push each unvisited neighbor.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Depth-first Search proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Adjacency-list DFSO(V + E)O(V + E)Reachable nodes and their outgoing edges are processed a bounded number of times.

Space

Recursive DFS uses O(V) visited storage plus O(depth) frames; this marks-on-pop component Lab can retain O(E) pending stack entries, in addition to O(V) visited storage.

Assumptions

  • An explicit stack that marks on pop may contain duplicate pending edges; include that storage rather than promising only O(depth).
  • A deep chain can raise RecursionError even though total work is linear.

Invariants Worth Saying Aloud

  1. A node is marked before traversing its outgoing edges, preventing recursive reentry through a cycle.
  2. Each depth argument belongs to that call; returning to a sibling restores the parent frame.

When To Use Or Avoid Depth-first Search

Use It When

  • Use DFS to finish a branch or compute a subtree result before its parent.
  • Use an explicit stack when graph depth can exceed Python recursion capacity.

Choose Another Tool When

  • Use BFS for shortest edge-count distances in an unweighted graph.
  • A single start explores only its reachable component, not all disconnected vertices.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Marking only after exploring a self-loop

If node 0 is not marked before its edge to itself, the edge appears to need another visit.

Prevent it: Mark before inspecting outgoing edges.

Avoid

should_recurse = neighbor not in seen
seen.add(node)

Use instead

seen.add(node)
should_recurse = neighbor not in seen

Sharing a mutable depth across siblings

Incrementing one shared depth makes the second child look deeper than the first even though both are one edge from the root.

Prevent it: Compute each child depth from the unchanged parent depth.

Avoid

depths = []
for child in children:
    depth += 1
    depths.append(depth)

Use instead

depths = []
for child in children:
    depths.append(depth + 1)

Reversing recursive neighbor order with a stack

Pushing [1,2] unchanged means pop visits 2 first. A requested recursive order visits 1 first.

Prevent it: Reverse neighbors before extending a LIFO stack when matching recursive order.

Avoid

stack.extend(neighbors)

Use instead

stack.extend(reversed(neighbors))

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.