Coding Pattern:

Graph Depth First Search

This pattern has a cheat sheet you can unlock.

Note

🛑 We strongly suggest getting comfortable with graphs before you start. Otherwise this section will be very confusing :)

Overview

Graph depth first search, usually just called depth first search (DFS), is the most straightforward way to traverse a graph.

DFS works especially well for two kinds of graph problems:

  1. Validation Problems ask whether something is true about a graph. Usually that means checking whether a node exists in the graph or whether two nodes are connected.
  2. Path Problems also ask for a path. Besides checking a condition, you also return the path to a node. For example, you might return the nodes of a cycle if the graph has one.

Note

You can solve a lot of DFS problems with breadth first search too. In interviews, DFS is usually the better pick because it's simpler and works for more problems. The backtracking pattern is actually DFS used in a particular way.

Pattern concept

Let's walk through a basic graph path problem:

Graph Depth First Search Slide 1: Find the path between node 0 and node 4 in the following graph:
Graph Depth First Search Slide 2: The first step is to build the graph from its edges...
Graph Depth First Search Slide 3: This graph is undirected, so remember to add each edge in both directions. So far: 0: [1], 1: [0].
Graph Depth First Search Slide 4: This graph is undirected, so remember to add each edge in both directions. So far: 0: [1], 1: [0, 2], 2: [1].
Graph Depth First Search Slide 5: This graph is undirected, so remember to add each edge in both directions. So far: 0: [1], 1: [0, 2], 2: [1, 3], 3: [2].
Graph Depth First Search Slide 6: This graph is undirected, so remember to add each edge in both directions. The full graph: 0: [1], 1: [0, 2, 4], 2: [1, 3], 3: [2], 4: [1].
Graph Depth First Search Slide 7: Set up your result list and visited set. res = [] and visited = {}.
Graph Depth First Search Slide 8: Our path should start at 0 and end at 4. start = 0 and target = 4.
Graph Depth First Search Slide 9: Starting with node 0, add it to the visited set and to the possible result. res = [0] and visited = {0}.
Graph Depth First Search Slide 10: Go to its unvisited neighbor, 1.
Graph Depth First Search Slide 11: Add node 1 to res and visited, then recurse into f(1). res = [0, 1] and visited = {0, 1}.
Graph Depth First Search Slide 12: Now that you're in node 1, go to its unvisited neighbors (2 and 4).
Graph Depth First Search Slide 13: Add node 2 to res and visited, then recurse into f(2). res = [0, 1, 2] and visited = {0, 1, 2}.
Graph Depth First Search Slide 14: Now that you're in node 2, go to its unvisited neighbor, 3.
Graph Depth First Search Slide 15: Add node 3 to res and visited, then recurse into f(3). res = [0, 1, 2, 3] and visited = {0, 1, 2, 3}.
Graph Depth First Search Slide 16: We still haven't found the target, and there are no more paths to try from here. Pop 3 from res and return.
Graph Depth First Search Slide 17: Back in f(2), we still haven't found the target, and there are no more paths to try. Pop 2 from res and return. res = [0, 1, 2] becomes [0, 1].
Graph Depth First Search Slide 18: Back in f(1), there's still an unvisited neighbor. Add node 4 to res and visited, then recurse into f(4). res = [0, 1, 4].
Graph Depth First Search Slide 19: We've reached the target! Return from the function and return res, which is [0, 1, 4].
1 / 19

Use ← → arrow keys

Solution templates

There are two templates for depth first search on a graph. Which one you use depends on what the question asks for:
  • Validation problems: you check whether a condition is true.
  • Path problems: you check a condition and also return the path you took.

Validation Problem

An example validation problem: Return whether node 0 is connected to node 4.

# === Recursive helper function ===
def dfs(curr: str, target: str, graph: Dict[str, List[str]], visited: Set):
  # === Visited Check ===
  visited.add(curr)

  # === Result Check ===
  if curr == target:
    return True
  
  # === Recursive Find ===
  # Check if recursing into ANY unvisited neighbors will reach the target.
  for node in graph[curr]:
    if node not in visited:
      if dfs(node, target, graph, visited):
        return True

  return False  # No neighbors led to the target.

# === Original function ===
def find_node(edges: List[List[str]], start: str, target: str) -> bool:
  # === Graph Initialization === 
  # Decide if we should build an undirected vs directed graph. 
  graph = defaultdict(list)
  for edge in edges:
    graph[edge[0]].append(edge[1])
    graph[edge[1]].append(edge[0])

  # === DFS Initialization ===
  visited = set()
  return dfs(start, target, graph, visited)
  
print(find_node([["0", "1"], ["1", "2"], ["2", "3"], ["1", "4"]], "0", "4"))
    
main.py

Path Problem

An example path problem: If node 0 is connected to node 4, return the path.

# ==== Recursive helper function ====
def dfs(curr: str, target: str, graph: Dict[str, List[str]], visited: Set, res: List[int]):
  # === Visited Check ===
  visited.add(curr)

  # === Result Check ===
  if curr == target:
    return True
  
  # === Recursive Find ===
  # Remember to update the result path BEFORE and AFTER
  # recursing into unvisited neighbors.
  for node in graph[curr]:
    if node not in visited:
      res.append(node)
      if dfs(node, target, graph, visited, res):
        return True
      res.pop()

  return False  # No neighbors led to the target.

# ==== Original function ====
def find_node(edges: List[List[str]], start: str, target: str) -> bool:
  # === Graph Initialization ===  
  # Decide if we should build an undirected vs directed graph.
  graph = defaultdict(list)
  for edge in edges:
    graph[edge[0]].append(edge[1])
    graph[edge[1]].append(edge[0])

  # === DFS Initialization ===
  visited = set()
  res = [start] 
  if dfs(start, target, graph, visited, res) == True:
    return res
  return []
  
print(find_node([["0", "1"], ["1", "2"], ["2", "3"], ["1", "4"]], "0", "4"))
    
main.py

Note

The code changes slightly depending on whether you build a directed or an undirected graph. Ask yourself this question to decide: is there a dependency between nodes in the graph?

How to identify

Does the problem involve any of these?

  • Finding the number of connected components in a graph
  • Exploring paths or connections between nodes in a graph
    • Return whether node A is connected to node B.
    • Return the path from node A to node B if they're connected.
    • Pacific Atlantic Water Flow: Return which cells on the grid can have water flowing to certain borders of the grid.
    • Course Schedule: Determine if a valid order exists between courses.
  • Exploring combinations that satisfy a condition (covered later)

Note

Depth first search usually takes O(n + e) time, where n is the number of nodes and e is the number of edges. A traversal visits each node and edge once.