Some data isn’t a line, a chain or a hierarchy. Things connect to other things. The connections can form loops, and the data can come in separate pieces. That’s a graph. The question you ask of one is almost always the same: what can I reach from here, how fast, and in what order?

You already know the tools for walking a graph. They are the DFS and BFS from Trees and the mark-and-explore recursion from Backtracking. Graphs add one thing trees never needed: a record of where you’ve already been.

Here is how the post is laid out. Directed cycle detection and ordering live inside the Adjacency List module. Union-Find gets its own short module at the end. All of it unlocks Advanced Graphs and 2-D DP.

How to use this post: the method. The checkpoints don’t show answers on the page. Work each one out yourself first, then open the linked chat to have your answer checked.

Intro to Graphs

Foundation

A graph has two parts. There is a set of vertices, also called nodes. And there is a set of edges, where each edge connects a pair of vertices. That’s the whole definition. Everything else describes the edges:

  • Directed or undirected. A follow on a social network is directed: I can follow you without you following me. A friendship is undirected, because it goes both ways. You can think of an undirected edge as two directed edges, one each way.
  • Cycles. A cycle is a path that comes back to where it started. Trees are exactly the graphs where this can’t happen.
  • Connected components. These are the separate pieces of the graph. A graph doesn’t have to be one piece.

We write V for the number of vertices and E for the number of edges. With V vertices there are at most V² directed edges. So E can be anywhere from 0 up to roughly V². That huge range is why the way you store a graph matters.

Mechanics

Interview problems hand you graphs in three shapes:

  1. A grid (matrix). Each cell is a vertex. Its neighbours are the cells up, down, left and right. The edges are never stored. You work them out from (r ± 1, c) and (r, c ± 1) when you need them.
  2. An adjacency matrix. This is a V × V table. matrix[u][v] == 1 means there is an edge u → v. Checking one edge is O(1). But the table always costs V² memory, however few edges there are.
  3. An adjacency list. Every vertex gets a list of its neighbours. It costs O(V + E) memory. A vertex’s degree, written deg(u), is the number of neighbours it has, so looping over u’s neighbours costs exactly deg(u). When you’re given a list of edges, this is what you build almost every time.

The worked example for this module has n = 5 vertices and the undirected edges [[0, 1], [0, 2], [1, 2], [3, 4]].

One property is worth remembering. In an undirected adjacency list, every edge shows up twice, once in each endpoint’s list. Edge [0, 1] puts 1 in 0’s list and 0 in 1’s list. So the list lengths (the degrees) add up to 2E. Here that’s 2 + 2 + 2 + 1 + 1 = 8, which is 2 × 4.

Diagram

Undirected graph, 5 vertices, 4 edges, two componentsEdges 0-1, 0-2, 1-2 form a triangle, component {0, 1, 2}; edge 3-4 is a separate component {3, 4}.undirected: 5 vertices, 4 edges01234component {0, 1, 2}component {3, 4}
Adjacency matrix and adjacency list of the example graphMatrix: 25 cells, 8 of them 1, one per stored edge direction. List: 0:[1,2] 1:[0,2] 2:[0,1] 3:[4] 4:[3], the same 8 entries.adjacency matrix01100101001100000001000100123401234uv25 cells, 8 are 1blue = an edge u – vadjacency list120:021:012:43:34:8 entries totalthe same 8 edges

Implementation

def to_matrix(n, edges, directed=False):
    # n x n table of 0/1; matrix[u][v] == 1 means an edge u -> v exists
    matrix = [[0] * n for _ in range(n)]
    for u, v in edges:
        matrix[u][v] = 1
        if not directed:
            matrix[v][u] = 1  # undirected edge {u, v} is stored in both cells
    return matrix


def to_adj_list(n, edges, directed=False):
    # adj[u] lists every v with an edge u -> v
    # All n keys are created up front, so a vertex with no edges still
    # appears (with n = 3 and no edges: {0: [], 1: [], 2: []}).
    adj = {u: [] for u in range(n)}
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)  # edge [0, 1] puts 1 in adj[0] and 0 in adj[1]
    return adj


edges = [[0, 1], [0, 2], [1, 2], [3, 4]]
print(to_adj_list(5, edges))
# {0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [4], 4: [3]}
print(to_adj_list(5, edges, directed=True))
# {0: [1, 2], 1: [2], 2: [], 3: [4], 4: []}

Filling in the edges takes O(E) for either one, once the empty structure exists. Setting up the empty matrix already costs O(V²) time and space. The list costs O(V + E) in total.

Recognition

  • Whenever the input is “n things and a list of pairs”, build an adjacency list first. That covers Course Schedule, Course Schedule II, Graph Valid Tree, Number of Connected Components In An Undirected Graph and Redundant Connection.
  • A 2-D grid where each cell relates to its neighbours is a graph whose edges are implicit (worked out, not stored). Don’t convert it to an adjacency list. Number of Islands, Max Area of Island, Walls And Gates, Rotting Oranges, Pacific Atlantic Water Flow and Surrounded Regions all work straight on the grid.
  • Clone Graph hands you the adjacency list already built into node objects (node.neighbors).
  • Reach for an adjacency matrix only when V is small and you need constant-time “is there an edge u → v?” checks.

Pitfalls

  • Forgetting the reverse edge for undirected input. Your traversal will then work from one side of the graph but not from the other.
  • Missing isolated vertices. Say you build with a defaultdict and never touch vertex k. Then adj has no key k. If you loop over adj instead of range(n), you skip k without any error. That matters when you’re counting components.
  • Self-loops in undirected input. With the code above, edge [0, 0] gives adj[0] == [0, 0], one append for each direction. A traversal doesn’t care, because 0 is already marked when it sees itself. But if you read len(adj[0]) as “number of distinct neighbours”, you get 2 for a vertex whose only neighbour is itself.
  • Choosing the matrix for a big sparse graph. Sparse means few edges compared to V². Take V = 10⁵ and E = 2 × 10⁵. The matrix has 10¹⁰ cells, while the list has only 4 × 10⁵ entries.

Active Recall

  1. The adjacency list above has 8 entries for 4 edges. Why? And how many would the directed version have?

  2. You need to answer “is there an edge between 3 and 4?” thousands of times. What does each representation cost per query, and how would you fix the list’s cost?

  3. How many connected components does the example graph have, and is the component containing vertex 0 a tree?

  4. A 4 × 4 grid with no walls is a graph. How many vertices does it have, what’s the maximum degree, and why wouldn’t you build an adjacency list for it?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: none of the problems on this list practises degree counting on its own. They all use the graph inside a traversal. So this checkpoint is included.

A town has n people labelled 1 to n. trust is a list of pairs [a, b] meaning “a trusts b”. No pair appears twice, and nobody trusts themselves. There’s a rumour that one person is the town judge. The judge trusts nobody, and everybody else trusts the judge. Return the judge’s label, or -1 if no such person exists. For example, n = 3 and trust = [[1, 3], [2, 3]] returns 3.

Before asking for help, write down: the observation, the approach, why it’s correct, the complexity.

Work it out, then talk it through withChatGPT ↗Claude ↗

Transfer test

You’re storing a social network with a billion users, each with about 200 friends, and the most common operation is “list this user’s friends”. Adjacency matrix or adjacency list? Would you use it? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Matrix DFS

Foundation

Think of the paint bucket tool in a drawing app. You click one pixel. Every same-coloured pixel connected to it changes colour, and the colour keeps spreading until it hits a boundary.

That’s depth-first search (DFS) on a grid. Go as deep as you can in one direction. When you’re blocked, back up and try the next direction. It answers “which cells can I reach from here?” And each time it reaches a cell, you can collect something from that cell.

Mechanics

The worked example is a 4 × 4 grid, with 0 for an open cell and 1 for a wall.

The 4 by 4 worked grid, 0 open and 1 wallRows: 0 0 0 1 / 1 0 0 0 / 1 0 1 0 / 0 1 0 0. Wall cells are hatched grey.the worked grid0001100010100100r0r1r2r3c0c1c2c30 = open1 = wall

Flood fill from (0, 0) marks every open cell it can reach as 2. It works like this:

  1. dfs(r, c) first checks three things: is the cell off the grid, is it a wall, or is it already marked? If any is true, return. This one guard is the base case.
  2. Otherwise, mark grid[r][c] = 2 before recursing.
  3. Recurse into the four neighbours.

Why does it matter that you mark before recursing? Follow the first step. (0, 0) recurses into (0, 1). But (0, 1) has (0, 0) as one of its neighbours. If (0, 0) were still 0 at that moment, (0, 1) would call back into it, and the two cells would call each other forever. I ran a version that marks after the recursive calls on this grid and got a RecursionError. When you mark first, (0, 1) looks back, sees 2, and stops.

An invariant is a fact that stays true the whole time the algorithm runs. Here it is: every cell is marked at most once, and once marked it is never explored again. That’s why the total work grows with the grid size and no faster.

Matrix DFS has a second classic use: counting the paths from the top-left to the bottom-right. That changes one thing. A cell can sit on many different paths. So a cell is marked only while it’s on the current path, and unmarked on the way back out. That’s the backtracking pattern.

The difference comes from the question. Flood fill asks “is this cell reachable?”, which has one answer per cell. Path counting asks “how many routes are there?”, and different routes can reuse the same cell.

Diagram

Order flood fill discovers cells from (0, 0)Directions tried down, up, right, left. Discovery order 1 to 10 starting at (0,0); walls are grey; (3,0) is open but never reached.flood fill from (0, 0): discovery orderdirections tried: down, up, right, left12635748109r0r1r2r3c0c1c2c3startreachedwallopen, never reached

Follow the numbers. DFS goes right to (0, 1), down to (1, 1), down to (2, 1), and hits a dead end. It backs up to (1, 1), goes right to (1, 2), up to (0, 2), and hits another dead end. It backs up to (1, 2), goes right to (1, 3), then down, down, left. (3, 0) is open, but walls box it in, so no path reaches it.

Path counting on the same grid finds exactly two simple paths to (3, 3). A simple path is one that never visits the same cell twice.

The two simple paths from (0,0) to (3,3)Path A goes down through (1,1); path B goes right through (0,2). Both take 6 moves and share (1,2), (1,3), (2,3). Walls are grey.every simple path from (0, 0) to (3, 3)r0r1r2r3c0c1c2c3path A: 6 movesr0r1r2r3c0c1c2c3path B: 6 moveswall

Implementation

def flood_fill(grid, r, c):
    """Mark every open (0) cell reachable from (r, c) as 2. Mutates grid."""
    rows, cols = len(grid), len(grid[0])

    def dfs(r, c):
        # One guard covers every reason to stop: off the grid, a wall (1),
        # or already marked (2). Only an unmarked open cell (0) gets past it.
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != 0:
            return
        grid[r][c] = 2  # mark BEFORE recursing: when (0, 1) looks back at (0, 0), it sees 2 and stops
        dfs(r + 1, c)   # down
        dfs(r - 1, c)   # up
        dfs(r, c + 1)   # right
        dfs(r, c - 1)   # left

    dfs(r, c)
    return grid


def count_paths(grid, r, c, visit):
    """Count simple paths from (r, c) to the bottom-right cell through open (0) cells."""
    rows, cols = len(grid), len(grid[0])
    if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 1 or (r, c) in visit:
        return 0
    if (r, c) == (rows - 1, cols - 1):
        return 1
    visit.add((r, c))  # (r, c) is on the CURRENT path only
    total = (count_paths(grid, r + 1, c, visit) + count_paths(grid, r - 1, c, visit)
             + count_paths(grid, r, c + 1, visit) + count_paths(grid, r, c - 1, visit))
    visit.remove((r, c))  # unmark: path A and path B both pass through (1, 2)
    return total


grid = [[0, 0, 0, 1],
        [1, 0, 0, 0],
        [1, 0, 1, 0],
        [0, 1, 0, 0]]
print(count_paths(grid, 0, 0, set()))  # 2
flood_fill(grid, 0, 0)
# grid is now [[2,2,2,1], [1,2,2,2], [1,2,1,2], [0,1,2,2]]; (3, 0) stays 0

Flood fill on an R × C grid takes O(R · C) time. Each cell is marked once, and each marked cell checks 4 neighbours. Space is O(R · C) for the recursion stack in the worst case, which is a long snake-shaped region where every call waits on the next. Path counting is exponential in the worst case, because it lists every path, and there can be far more paths than cells.

Edge cases I ran:

  • Starting on the wall at (0, 3) marks nothing.
  • Starting on the isolated (3, 0) marks only (3, 0).
  • A 1 × 1 grid [[0]] becomes [[2]].
  • For path counting, [[0]] gives 1, [[0, 1], [1, 0]] gives 0, and an open 2 × 2 gives 2.

Recognition

  • Signals: a grid, plus words like “connected”, “region”, “island”, “enclosed”, “reachable” or “flows to”. The question is about a whole group of cells, not the distance to one of them.
  • On this list: Number of Islands, Max Area of Island, Pacific Atlantic Water Flow and Surrounded Regions all show these signals.
  • Not DFS when the question is “fewest steps” or “minimum time”. DFS reaches a cell by whichever path it tries first, which may not be the shortest one. That job belongs to BFS, the next module.
  • Flood fill or path enumeration? Flood fill marks cells for good. Path enumeration marks and then unmarks. If the answer depends on the route taken, you’re backtracking, and the cost is exponential.

Pitfalls

  • Marking after recursing causes infinite recursion (the RecursionError above).
  • Recursion depth. An all-open 200 × 200 grid can need a call stack 40,000 frames deep. CPython’s default limit is 1000 (recalled; sys.getrecursionlimit() printed 1000 on my machine). Use an explicit stack instead (the Iterative DFS pattern from Trees), or raise the limit.
  • Changing input you’re not allowed to touch. If the grid must stay as it was, keep a separate visited set. That costs O(R · C) extra space.
  • Checking bounds in the wrong order. Check 0 <= r < rows before you read grid[r][c]. Python’s grid[-1] doesn’t crash. It quietly reads the last row.
  • Forgetting to unmark in path counting. I ran the version without visit.remove, and it returns 1 instead of 2. Path A’s marks are left behind and block path B.

Active Recall

  1. Why must grid[r][c] = 2 happen before the four recursive calls, and not after them?

  2. On the example grid, what does flood_fill(grid, 3, 0) mark? And flood_fill(grid, 0, 3)?

  3. flood_fill never unmarks, but count_paths does. What goes wrong if count_paths stops unmarking?

  4. What are the time and space costs of flood fill on an R × C grid, and what’s the worst-case shape for space?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Skipped for this module. Pacific Atlantic Water Flow and Surrounded Regions each make you work out how to apply flood fill, not just run it. So you’ll practise that reasoning when you solve them.

Transfer test

An image editor’s “magic wand” selects every pixel connected to the clicked pixel whose colour is within a tolerance of the clicked colour. Images are up to 4000 × 3000. Would you use matrix DFS? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Matrix BFS

Foundation

Drop a stone in a pond. The ripple reaches everything 1 unit away, then everything 2 units away, then 3. Breadth-first search (BFS) works the same way. It visits cells in rings, where every cell in a ring is the same distance from the start. So the first time BFS reaches a cell, it got there by the shortest route. It answers “what’s the fewest number of moves?” when every move costs the same.

Mechanics

We use the same grid and the same start, (0, 0), with (3, 3) as the target.

  1. Put the start in a queue and mark it seen.
  2. Process the queue one layer at a time. A layer is one ring: all the cells at the same distance. Read len(q) once, pop exactly that many cells, and push their unseen open neighbours. When the layer is done, do steps += 1.
  3. When the target is popped, return steps.

The invariant (the fact that stays true at every step) is this: at the start of each layer, the queue holds exactly the cells at distance steps, and every closer cell has already been popped.

Why does it hold? A cell’s neighbours are at most one step further away than the cell itself. So everything pushed during layer k is at distance k + 1. And no shorter route can turn up later, because every shorter distance was fully processed first.

Mark cells when you enqueue them, not when you pop them. A cell can be next to several cells in the current layer. If you mark it on push, it enters the queue only once. If you wait until it’s popped, each of those neighbours can push it again, so duplicates get in. I counted pushes: 10 versus 11 on this grid, and 9 versus 13 on an open 3 × 3.

Now the multi-source variant. Say there are several starting cells. Push all of them at distance 0 before the loop starts. Every cell then gets its distance to the nearest source.

Why is that correct? Imagine adding one extra vertex that is joined to every source, and running ordinary BFS from it. That’s the same thing. Every distance shifts by one layer, and nothing else changes, in the reasoning or in the code.

Diagram

BFS distance of every cell from (0,0), layer by layerDistances 0 1 2 # / # 2 3 4 / # 3 # 5 / . # 7 6, which is also the layer each cell pops in. Target (3,3) popped in layer 6; (3,0) is never reached.BFS from (0, 0): distance = the layer a cell pops in0122343576r0r1r2r3c0c1c2c3never reachedwalllayer 0: (0,0) sourcelayer 1: (0,1)layer 2: (1,1) (0,2)layer 3: (2,1) (1,2)layer 4: (1,3)layer 5: (2,3)layer 6: (3,3) target, answer 6layer 7: (3,2) only if you keep going
Multi-source BFS: distance to the nearest of (0,0) and (3,3)Both sources seeded at distance 0. Distances 0 1 2 # / # 2 3 2 / # 3 # 1 / . # 1 0. Cells (1,3), (2,3), (3,2) were 4, 5, 7 with one source.two sources, both seeded at distance 0each number = distance to the nearer source0122323110r0r1r2r3c0c1c2c3was 4was 5was 7sourcecloser than one sourcewall

With (3, 3) added as a second source, (1, 3) drops from 4 to 2, because (3, 3) is closer to it. (3, 2) drops from 7 to 1.

Implementation

from collections import deque


def shortest_path(grid, sources, target):
    """Fewest moves from any cell in `sources` to `target` through open (0) cells; -1 if unreachable."""
    rows, cols = len(grid), len(grid[0])
    q = deque()  # (recalled: deque.popleft is O(1); list.pop(0) is O(n))
    seen = set()
    for r, c in sources:
        if grid[r][c] == 0:
            q.append((r, c))
            seen.add((r, c))  # mark on ENQUEUE, so each cell is pushed at most once
    steps = 0
    while q:
        # Invariant: q holds exactly the cells at distance `steps` from the
        # nearest source. With source (0, 0): steps = 2 -> q = [(1, 1), (0, 2)].
        for _ in range(len(q)):  # range(len(q)) is evaluated once, so only this layer is popped
            r, c = q.popleft()
            if (r, c) == target:
                return steps
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0 and (nr, nc) not in seen:
                    seen.add((nr, nc))
                    q.append((nr, nc))
        steps += 1
    return -1  # queue ran dry: target is in a different region, like (3, 0)


grid = [[0, 0, 0, 1],
        [1, 0, 0, 0],
        [1, 0, 1, 0],
        [0, 1, 0, 0]]
print(shortest_path(grid, [(0, 0)], (3, 3)))          # 6
print(shortest_path(grid, [(0, 0)], (3, 0)))          # -1
print(shortest_path(grid, [(0, 0), (3, 3)], (1, 3)))  # 2
print(shortest_path([[0]], [(0, 0)], (0, 0)))         # 0
print(shortest_path([[1]], [(0, 0)], (0, 0)))         # -1: the only source is a wall

Time is O(R · C). Each cell is pushed and popped at most once, and each one checks 4 neighbours. Space is O(R · C) for seen and the queue.

Recognition

  • Signals: “minimum number of steps / moves / minutes / transformations”, where every move costs the same. If the answer is a count of hops, think BFS.
  • Several starting points spreading at the same time means multi-source BFS. Look for phrases like “every X affects its neighbours each minute” or “distance to the nearest Y”. Walls And Gates and Rotting Oranges show this signal.
  • The graph doesn’t have to be a grid. Word Ladder asks for a minimum number of transformations. So it’s BFS over vertices you generate yourself.
  • Not BFS when moves have different costs. That’s Dijkstra (Advanced Graphs). And you don’t need BFS when you only care whether a cell is reachable, not how far away it is. DFS is simpler there.

Pitfalls

  • Marking on pop lets duplicates into the queue: 11 versus 10 pushes here, and 13 versus 9 on an open 3 × 3. The answer is still right, but you do more work. With several sources, it’s also easy to count a cell twice.
  • Adding 1 to steps on every pop instead of every layer. Then steps counts how many cells you’ve processed, not the distance.
  • Returning steps off by one. Decide whether you count moves (start = 0) or cells on the path (start = 1). Then check against a 1 × 1 grid. Here [[0]] returns 0.
  • Using a list as the queue. list.pop(0) shifts every remaining element along by one, so the loop becomes quadratic.
  • A blocked source. If the start cell is a wall, return -1 before the loop. That’s what the grid[r][c] == 0 check in the seeding loop does.

Active Recall

  1. Why is the first time BFS pops (3, 3) guaranteed to give the shortest distance?

  2. Marking on enqueue gave 10 pushes on this grid. Marking on pop gave 11. Where does the extra push come from?

  3. With sources (0, 0) and (3, 3) seeded together, (3, 2) gets distance 1. What does each number in that grid mean now, and why does seeding both at distance 0 produce it?

  4. What breaks if you replace the for _ in range(len(q)) loop with a plain while q: that pops one cell and then does steps += 1?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Skipped for this module. In Word Ladder you have to work out from scratch what counts as a vertex and what counts as a neighbour, before any BFS runs. You’ll practise that when you solve it.

Transfer test

A warehouse robot moves on a grid. Most floor tiles take 1 second to cross, but some are sticky and take 5 seconds. You want the fastest route from dock to shelf. Would you use matrix BFS? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Adjacency List

Foundation

Grids come with their edges built in. Most other graphs arrive as a list of pairs, and you build the adjacency list yourself, as in the first module. After that, DFS and BFS work exactly as they did on grids. The only change is that “the four neighbours” becomes “adj[u]”.

The new thing is direction. A directed edge u → v means “u leads to v”, or “u must come before v”. That raises a question grids never did: can following the arrows bring you back to where you started? Think of dependencies, like “build step u must run before step v”. If the arrows form a loop, no valid order exists. If there’s no loop, you want an order.

Mechanics

The worked example has 6 build steps and the directed edges [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4], [5, 4]]. Here u → v means “u before v”.

BFS on an adjacency list is the Matrix BFS loop, with for v in adj[u] as the neighbour loop. From 0, the fewest hops to 4 is 3 (0 → 1 → 3 → 4). From 4 to 0 the answer is -1, because edges only go one way.

Directed cycle detection with three colours. In a directed graph, a plain visited set isn’t enough (we’ll see why in a moment). Instead, every vertex gets a colour:

  • WHITE: not visited yet.
  • GRAY: visited, and still on the current recursion path. In other words, we’re still inside its dfs call.
  • BLACK: finished. Every vertex reachable from it has been explored, and none of them led back.

When dfs(u) looks at a neighbour v, there are three cases:

  • v is GRAY. Then v is an ancestor of u on the current path. So there’s already a path v → … → u, and the edge u → v closes it into a cycle. Report the cycle.
  • v is WHITE. Recurse into v.
  • v is BLACK. Skip v.

Is skipping a BLACK vertex safe? For u → v to be part of a cycle, v would need a path back to u. If v had one, v’s own DFS would have walked it. Then one of two things would have happened:

  • It met u as GRAY, and reported the cycle.
  • It found u WHITE, visited it and finished it. Then u would already be BLACK, and couldn’t be GRAY now.

Neither happened, so that path back to u doesn’t exist.

The BLACK case is why two colours (visited or not) aren’t enough. In the example, 0 → 1 → 3 and 0 → 2 → 3 both reach 3. This shape is called a diamond. When dfs(2) looks at 3, 3 has already been visited through 1. But that’s two routes to the same place, not a loop. A graph with directions and no cycles is called a DAG (directed acyclic graph). I ran a visited-only version on this DAG, and it wrongly reports a cycle.

Getting an order for free. Record each vertex at the moment it turns BLACK. This finishing order is called the postorder. Then reverse the list. In the reversed list, u comes before v for every edge u → v.

Why does that work? When dfs(u) examines v, v is either WHITE or BLACK. (GRAY would mean a cycle.) If v is WHITE, dfs(u) recurses into it, so v finishes first. If v is BLACK, it has already finished. Either way, v finishes before u. So v is earlier in the postorder, which puts it later in the reversed list.

Finally, loop over every vertex and start a DFS from each one that is still WHITE. Not every vertex is reachable from vertex 0. Vertex 5 isn’t.

Diagram

Six build steps as a directed graphAn edge u to v means u before v. Edges 0-1, 0-2, 1-3, 2-3, 3-4, 5-4; dashed red 4-1 is added only for the cycle run.six build steps: u → v means u before v012345added only in the cycle run
Three-colour DFS trace on the build-step graphRun on the six real edges, without 4 to 1. Each row shows the colour of vertices 0 to 5 after the event (plain WHITE, amber GRAY on the current path, green BLACK finished), and the postorder list. Reversed postorder is 5 0 2 1 3 4.three-colour DFS on the six edges (no 4 → 1)WHITE: unvisitedGRAY: on current pathBLACK: finishedeventcolour of 0 … 5postorderenter 0012345enter 1012345enter 3012345enter 4012345adj[4] = []finish 4012345post = [4]finish 3012345post = [4, 3]finish 1012345post = [4, 3, 1]enter 20123453 is BLACK: skipfinish 2012345post = [4, 3, 1, 2]finish 0012345post = [4, 3, 1, 2, 0]enter 5012345outer loop; 4 is BLACK: skipfinish 5012345post = [4, 3, 1, 2, 0, 5]reversed: [5, 0, 2, 1, 3, 4], every edge u → v has u before v
Back edge 4 to 1 found while 0, 1, 3, 4 are GRAYWith 4 to 1 added, DFS reaches 4 along the GRAY path 0 1 3 4; edge 4-1 points at GRAY vertex 1, closing the cycle 1 3 4 1.with 4 → 1 added, DFS standing at 4GRAY: on current path012345back edge: 1 is GRAYcycle 1 → 3 → 4 → 1

Implementation

from collections import deque

WHITE, GRAY, BLACK = 0, 1, 2


def build(n, edges):
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)  # directed: u -> v only
    return adj


def bfs_hops(adj, src, dst):
    q, seen, steps = deque([src]), {src}, 0
    while q:
        for _ in range(len(q)):  # one layer = every vertex exactly `steps` hops from src
            u = q.popleft()
            if u == dst:
                return steps
            for v in adj[u]:
                if v not in seen:
                    seen.add(v)
                    q.append(v)
        steps += 1
    return -1


def cycle_or_order(n, adj):
    """Return (True, []) if a directed cycle exists, else (False, order) with u before v for every edge u -> v."""
    color = [WHITE] * n
    post = []

    def dfs(u):
        color[u] = GRAY  # u is on the current recursion path
        for v in adj[u]:
            if color[v] == GRAY:
                return True  # v is an ancestor of u still on the path: edge u -> v closes a loop (4 -> 1 above)
            if color[v] == WHITE and dfs(v):
                return True
            # color[v] == BLACK: v already finished without reaching a GRAY vertex,
            # so edge u -> v can't be part of a cycle (edge 2 -> 3 above)
        color[u] = BLACK  # every path out of u explored, none looped back
        post.append(u)    # v finished before u for every edge u -> v
        return False

    for u in range(n):  # vertices 0..n-1: vertex 5 is not reachable from 0, so this loop is what finds it
        if color[u] == WHITE and dfs(u):
            return True, []
    return False, post[::-1]


edges = [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4], [5, 4]]
adj = build(6, edges)
print(bfs_hops(adj, 0, 4), bfs_hops(adj, 4, 0))  # 3 -1
print(cycle_or_order(6, adj))                    # (False, [5, 0, 2, 1, 3, 4])
print(cycle_or_order(6, build(6, edges + [[4, 1]])))  # (True, [])

Edge cases I ran:

  • A single vertex with no edges gives (False, [0]).
  • A self-loop [[0]] gives (True, []), because 0 is GRAY when it sees itself.
  • Three isolated vertices give (False, [2, 1, 0]). That’s a valid order, because there are no edges to break.
  • 0 → 1, 1 → 0 gives (True, []).

Time is O(V + E). Each vertex goes WHITE → GRAY → BLACK once, and each edge is examined once, from its source. Space is O(V) for the colours and the recursion stack, plus the O(V + E) adjacency list.

Recognition

  • Signals: “n items and a list of pairs”, “dependencies”, “prerequisites”, “must happen before”, “is it possible to finish”, “return an order”. Course Schedule and Course Schedule II show the directed cycle and ordering signals. Number of Connected Components In An Undirected Graph and Graph Valid Tree show the signals for an undirected graph with its edges given explicitly.
  • Clone Graph gives you the adjacency list as objects. There, the seen structure can be a dict that maps each vertex to something you’ve built for it, not just a set.
  • Three colours are for directed graphs. In an undirected graph you can detect a cycle by asking “have I seen this vertex, and is it not the vertex I just came from?” Union-Find (the next module) also works.
  • Kahn’s algorithm is the BFS way to get the same order. It repeatedly removes vertices with in-degree 0, meaning no arrows point into them. It’s taught with Topological Sort in Advanced Graphs.

Pitfalls

  • Two colours in a directed graph report false cycles on diamonds. The visited-only version I ran says “cycle” on this DAG.
  • Three colours on an undirected graph. Edge {0, 1} is stored as both 0 → 1 and 1 → 0. So dfs(1) sees 0 as GRAY and reports a cycle on a single edge. I ran it, and it did. For undirected graphs, pass along the parent (the vertex you came from) and skip it.
  • Getting the edge direction backwards. Problem statements often say “[a, b] means b before a”. If you flip it, cycle detection still works, but the order comes out reversed. Check one pair by hand.
  • Starting only from vertex 0. Vertices you can’t reach from 0 never get coloured. So they’re missing from the order, and any cycles among them go undetected.
  • Forgetting to return early once a cycle is found. The order then holds a half-built, meaningless list.
  • Recursion depth. A dependency chain of 10⁴ vertices goes past the default recursion limit of 1000 (recalled).

Active Recall

  1. bfs_hops(adj, 0, 4) is 3, but bfs_hops(adj, 4, 0) is -1. Why doesn’t reachability go both ways here, when it did in the Intro example?

  2. When dfs(2) examines 3, 3 is BLACK. Why is skipping it safe, and what would a visited-only check have done?

  3. Show that the reversed postorder [5, 0, 2, 1, 3, 4] has u before v for the edges 2 → 3 and 5 → 4, and explain why that holds for every edge.

  4. With edge 4 → 1 added, which vertices are GRAY at the moment the cycle is detected, and which of them are on the cycle?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Skipped for this module. Course Schedule and Course Schedule II make you model the input as a directed graph yourself, and work out what the answer means in graph terms. You’ll practise that when you solve them.

Transfer test

A spreadsheet recalculates when a cell changes. Each cell’s formula may reference other cells, and circular references must be reported as errors. Would you use the adjacency-list DFS with three colours? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Union-Find

The problems below also need this. Redundant Connection, Graph Valid Tree and Number of Connected Components In An Undirected Graph all ask whether parts of an undirected graph are connected, while edges arrive one at a time. Union-Find answers those questions in near-constant time per edge.

Foundation

Picture companies merging. Every company has one CEO at the top. Want to know whether two employees work for the same company? Each one walks up the reporting chain to their CEO, and you compare the two CEOs.

When two companies merge, one CEO starts reporting to the other. The whole company comes along in that one move. Union-Find (also called a disjoint set union, or DSU) works exactly like that. It keeps track of groups that only ever merge, and it answers “same group?” fast.

Mechanics

The only state is parent[x] for each vertex. A vertex with parent[x] == x is a root. The root stands for its whole group, like the CEO.

  • find(x): follow parent until you reach a root. That root names x’s group. Path compression is a speed-up: after finding the root, point every vertex on the way directly at it. Then the next find from any of them takes one hop.
  • union(a, b): find both roots. If they’re the same, a and b are already connected, so return False. Otherwise attach one root under the other and return True. Union by size is the second speed-up: always attach the smaller tree under the larger one, so trees stay shallow.

Why does union by size keep trees shallow? A vertex only gets one level deeper when its tree is attached under a tree at least as big. That at least doubles the size of the tree the vertex belongs to. A size can double at most log₂ n times before it reaches n. So the depth stays at or below log₂ n.

Add path compression on top, and the amortised cost per operation is O(α(n)). Amortised means averaged over a long run of operations: a single call can be slower, but the total stays low. α is the inverse Ackermann function, which is below 5 for any practical n (recalled, not derived here).

The invariant: two vertices have the same root if and only if the edges processed so far connect them. So a union that returns False means the edge joins two vertices that were already connected. In an undirected graph, that edge closes a cycle.

The worked example has n = 6, with the edges processed in this order: (0, 1), (2, 3), (1, 2), (4, 5), (0, 3).

Diagram

Union-Find parent array after each unionparent goes from 0..5 to [0,0,0,0,4,4]. Amber marks the entry each union set; the last union returns False and path compression rewrites only parent[3] (cyan).parent[i] after each union012345002345002245000245000244000044startunion(0,1) Trueunion(2,3) Trueunion(1,2) Trueunion(4,5) Trueunion(0,3) False012345i6 componentssize[0]=2, 5 compssize[2]=2, 4 compssize[0]=4, 3 compssize[4]=2, 2 compsno merge, 2 compsunion(1,2): sizes tie at 2, so root 2 goes under root 0union(0,3): find(3) climbs 3 → 2 → 0, then sets parent[3] = 0set by the unionrewritten by path compression
Union-Find forest before and after find(3) compresses the pathArrows point to each vertex's parent; roots 0 and 4. Before: 3 under 2 under 0, 1 under 0, 5 under 4. After: 1, 2, 3 all directly under 0; 3 is the vertex path compression moved.before union(0,3)012345rootrootdepth 2after012345rootrootmoved: depth 1arrows point to parent

Implementation

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))  # every vertex 0..n-1 starts as its own root
        self.size = [1] * n           # size[r] is only meaningful while r is a root
        self.components = n

    def find(self, x):
        root = x
        while self.parent[root] != root:  # climb until a vertex is its own parent
            root = self.parent[root]
        while self.parent[x] != root:     # path compression: point every vertex on the path at root
            self.parent[x], x = root, self.parent[x]  # find(3): parent[3] 2 -> 0, then x = 2, whose parent is already 0
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False  # union(0, 3): find(0) == find(3) == 0, so edge (0, 3) adds no new connection
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra  # union by size: rb is now the root of the smaller (or equal) tree
        self.parent[rb] = ra  # union(1, 2): ra = 0, rb = 2, both size 2, so 2 goes under 0
        self.size[ra] += self.size[rb]
        self.components -= 1  # two separate groups became one
        return True


d = DSU(6)
for a, b in [(0, 1), (2, 3), (1, 2), (4, 5), (0, 3)]:
    print(a, b, d.union(a, b))
print(d.parent, d.components)  # [0, 0, 0, 0, 4, 4] 2

Edge cases I ran: DSU(1).union(0, 0) returns False and leaves 1 component. On DSU(3), union(0, 1) returns True, then union(1, 0) returns False, leaving 2 components.

Time is O(α(n)) amortised per find or union (recalled). So n vertices and E edges cost O(n + E · α(n)) in total. Space is O(n).

Recognition

  • Signals: the question is about connectivity in an undirected graph. Edges arrive one at a time, or all at once in no useful order. You see phrases like “are these connected”, “how many groups” or “which edge first created a cycle”. Groups only merge, never split. Redundant Connection, Graph Valid Tree and Number of Connected Components In An Undirected Graph show these signals.
  • Compared with DFS/BFS: both can answer connectivity. A traversal needs the whole graph up front, and it can give you paths and distances. Union-Find handles edges one at a time and needs no adjacency list. But it can’t tell you a path or a distance.
  • Not for directed graphs. Union-Find forgets direction. Edges 0 → 1, 1 → 2, 0 → 2 contain no directed cycle, yet union(0, 2) returns False.
  • Not when edges get deleted. There’s no cheap way to split a group.

Pitfalls

  • Comparing parent[a] == parent[b] instead of find(a) == find(b). After union(1, 2) above, parent[3] == 2 and parent[1] == 0. The parents differ, but 1 and 3 are connected.
  • Attaching a vertex instead of a root. Writing parent[a] = b without finding the roots first can cut a out of the group it was already in.
  • Skipping both speed-ups. I unioned a chain the naive way (0 under 1, 1 under 2, …) and got parent = [1, 2, 3, 4, 4]. That’s a single path of height 4, so each find degrades to O(n).
  • 1-indexed input. If vertices are labelled 1..n, allocate n + 1 slots, or subtract 1 everywhere.
  • Counting components with a separate pass over parent instead of over find(i). A non-root’s parent entry is just the next step up, not its group’s name.

Active Recall

  1. After union(1, 2), parent = [0, 0, 0, 2, 4, 5]. What does find(3) do, step by step, and what does parent look like afterwards?

  2. union(0, 3) returned False. What does that say about the graph built from these five edges?

  3. Without union by size and path compression, unioning 0-1, 1-2, 2-3, 3-4 produced parent = [1, 2, 3, 4, 4]. What does find(0) cost, and how does union by size prevent that shape?

  4. Why can’t Union-Find replace three-colour DFS for directed cycle detection?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: every problem on this list that uses Union-Find hands you the edges to union. None of them makes you notice, on your own, that some relation in the input behaves like connectivity. So this checkpoint is included.

You’re given equations over single lowercase letters, each either "x==y" or "x!=y" (always 4 characters). Return True if you can assign an integer to every letter so that all equations hold at the same time. For example, ["a==b", "b!=c", "c==a"] returns False, and ["a==b", "b==c", "a==c"] returns True.

Before asking for help, write down: the observation, the approach, why it’s correct, the complexity.

Work it out, then talk it through withChatGPT ↗Claude ↗

Transfer test

A network monitoring tool tracks which servers can reach each other. Cables get plugged in and unplugged all day, and operators constantly ask “can server A reach server B right now?”. Would you use Union-Find? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Integration

Every problem in this topic comes down to walking some graph. The main choice is what “visited” means.

  • Intro to Graphs tells you what shape you’re holding. A grid means you compute neighbours. A list of pairs means you build an adjacency list. Node objects mean the list is already built.
  • Matrix DFS and the DFS half of Adjacency List answer “what can I reach?” They mark a vertex as visited for good.
  • Matrix BFS answers “how few steps?” It uses the same kind of mark, but sets it at enqueue time. It works layer by layer, starting from one source or many.
  • Three colours stretch “visited” into “visited, and still on my current path”. That’s what directed cycles and dependency orders need.
  • Union-Find answers undirected connectivity without walking the graph at all. It takes one edge at a time.

How to choose between competing approaches:

The question Reach for Not
Which cells/vertices are connected to this one? DFS (or BFS, same set) Union-Find unless edges stream in
Fewest moves, all moves equal cost BFS, layer by layer DFS (first path found isn’t the shortest)
Nearest of several sources, for every cell Multi-source BFS, all sources at distance 0 One BFS per source
Can these dependencies be satisfied? Give an order Three-colour DFS + reversed postorder Visited-only DFS (false cycles)
Does this undirected edge close a cycle? How many groups? Union-Find, or DFS with a parent check Three colours (flags every edge)
Moves cost different amounts Dijkstra (Advanced Graphs) BFS

A recognition checklist for an unfamiliar problem:

  1. What are the vertices and what are the edges? If the statement doesn’t say, what changes one state into another?
  2. Directed or undirected? Does a pair [a, b] mean “a before b” or “b before a”?
  3. What’s the question: reachability, count of groups, minimum steps, an order, or a cycle?
  4. Minimum steps with equal costs means BFS. Everything else starts as DFS unless edges stream in, which means Union-Find.
  5. What does “visited” mean here: permanent, only on the current path (backtracking), or GRAY/BLACK?
  6. When is a vertex marked (before recursing, on enqueue), and what prevents an infinite loop?
  7. Is every component covered? Do you need an outer loop over all vertices or cells?
  8. What’s the recursion depth? Past about 1000, go iterative.

The problems

Work through these with the solving cycle from Part 1. Give each problem a 15-minute struggle, write down the one key sentence in your own words, then review it with spaced repetition.

For graphs, spend the struggle like this:

  • Sketch a small example first.
  • Decide whether it’s DFS, BFS, Dijkstra or a topological sort. Decide whether you need cycle detection or just a visited set.
  • Simulate it by hand before you code.
  • Then explain the order your traversal visits things in, and exactly how your code avoids infinite loops.

Take this lesson as a live session

If you’d rather be taught this interactively, with the coach waiting for your answers, open the full lesson prompt in a chat (it covers the four prerequisites, so ask for Union-Find at the end if you want that too).

Open the full lesson inChatGPT ↗Claude ↗