CodingPatterns9 min read

Graphs

A graph is any set of things connected by relationships: cities and roads, courses and prerequisites, cells in a grid and their neighbors, accounts that share an email. Interview graph problems rarely say "graph". They describe the things and the connections, and the first point you can score is recognizing that a graph is underneath. After that, five tools cover nearly everything: breadth-first search, depth-first search, topological sort, Dijkstra's algorithm and union-find. This lesson shows when each one fits, with Python you can trace by hand. It is for software and data candidates at any level; a later section says what changes as the bar rises.

How graph problems are judged

The SmartIntervu coding report scores problem solving, correctness, code quality, testing and edge cases, and communication. Graph problems are mostly decided in problem solving: naming the nodes, the edges and whether the edges are directed or weighted, then choosing the algorithm that matches. Correctness is usually lost on the visited set: forgetting it (infinite loops on cycles) or updating it at the wrong moment (duplicate work). Good tests include a disconnected graph, a cycle, a single node and an unreachable target.

Step one: build the graph

Before choosing an algorithm, say what a node is and what an edge is, then build an adjacency list: a map from each node to its neighbors.

from collections import defaultdict, deque


def build_graph(edges: list[tuple[int, int]], directed: bool) -> dict[int, list[int]]:
    graph: dict[int, list[int]] = defaultdict(list)
    for a, b in edges:
        graph[a].append(b)
        if not directed:
            graph[b].append(a)
    return graph

An adjacency list uses O(V + E) space and lets you loop over a node's neighbors directly. An adjacency matrix (V by V) only pays off when the graph is dense or you need constant-time "is there an edge between a and b?" checks.

A grid is a graph you never have to build. Each cell is a node, and its neighbors are the cells up, down, left and right that are inside the bounds and not blocked. Write the neighbor check once and reuse it.

The cue

  • "fewest steps", "minimum moves", "shortest path" with every step costing the same: BFS.

  • "count the separate groups", "can you reach", "fill a region": DFS or BFS, whichever you write faster.

  • "order the tasks so each comes after its prerequisites", "is there a valid order", "detect a cycle in dependencies": topological sort.

  • "cheapest", "fastest", "minimum total cost" with different edge costs: Dijkstra.

  • "connections arrive one at a time; are these two connected now?", "merge groups": union-find.

BFS: shortest paths when every step costs the same

BFS explores nodes in order of distance from the start, so the first time it reaches the target, it has found a shortest path. This finds the fewest moves between two cells of a grid, where # marks a wall:

def shortest_path(
    grid: list[str], start: tuple[int, int], goal: tuple[int, int]
) -> int:
    rows, cols = len(grid), len(grid[0])
    queue = deque([(start, 0)])
    seen = {start}
    while queue:
        (r, c), dist = queue.popleft()
        if (r, c) == goal:
            return dist
        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] != "#"
                and (nr, nc) not in seen
            ):
                seen.add((nr, nc))  # mark on enqueue, not on dequeue
                queue.append(((nr, nc), dist + 1))
    return -1

Trace it on a 2-by-3 grid with rows "..." and ".#.", from (0, 0) to (1, 2). Distance 1 reaches (1, 0) and (0, 1). Distance 2 reaches (0, 2), since (1, 1) is a wall. Distance 3 reaches (1, 2). The answer is 3.

Mark a cell as seen when you add it to the queue. If you mark it when you remove it, the same cell can be queued many times by different neighbors before it is processed, which inflates the work and can blow up memory on large grids. Time and space are O(V + E), which for a grid is O(rows times columns).

A useful variant is multi-source BFS: put every starting point in the queue at distance 0. It answers "distance from each cell to the nearest exit" or "how many minutes until every cell is reached" in one pass instead of one search per source.

DFS: reachability and connected components

When you only need to know what is reachable, not how far, DFS is just as good and often shorter. Counting connected components means starting a search from every node not yet seen:

def count_components(n: int, edges: list[tuple[int, int]]) -> int:
    graph = build_graph(edges, directed=False)
    seen: set[int] = set()
    count = 0
    for start in range(n):
        if start in seen:
            continue
        count += 1
        stack = [start]
        seen.add(start)
        while stack:
            node = stack.pop()
            for nxt in graph[node]:
                if nxt not in seen:
                    seen.add(nxt)
                    stack.append(nxt)
    return count

Looping over range(n) rather than over the edges matters: a node with no edges is still a component, and a solution that only walks the edge list misses it. The stack is explicit because a recursive DFS on a 1,000 by 1,000 grid can go a million calls deep, far past Python's recursion limit. With 5 nodes and edges (0, 1), (1, 2), (3, 4), the function returns 2.

Topological sort: ordering with dependencies

If edge (a, b) means "a must come before b", a valid order exists only when the directed graph has no cycle. Kahn's algorithm builds the order by repeatedly taking a node with no remaining prerequisites:

def topo_order(n: int, prereqs: list[tuple[int, int]]) -> list[int] | None:
    graph = build_graph(prereqs, directed=True)
    indegree = [0] * n
    for _, b in prereqs:
        indegree[b] += 1
    queue = deque(i for i in range(n) if indegree[i] == 0)
    order: list[int] = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph[node]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return order if len(order) == n else None  # None means a cycle

With n = 3 and edges (0, 1) and (1, 2), the in-degrees are 0, 1 and 1. Node 0 leaves first, which frees 1, which frees 2: the order is 0, 1, 2. With edges (0, 1) and (1, 0), no node starts at in-degree 0, the order stays empty, and the function returns None. That length check is the cycle detection, so one algorithm answers both "give me an order" and "is this possible". It runs in O(V + E).

Dijkstra: shortest paths with costs

When edges have different non-negative costs, BFS's "first arrival is shortest" no longer holds. Dijkstra's algorithm uses a min-heap to always expand the node with the smallest known distance:

import heapq


def dijkstra(graph: dict[int, list[tuple[int, int]]], source: int) -> dict[int, int]:
    dist = {source: 0}
    heap = [(0, source)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist[node]:
            continue  # a stale entry: a shorter path was already found
        for nxt, weight in graph.get(node, []):
            nd = d + weight
            if nd < dist.get(nxt, float("inf")):
                dist[nxt] = nd
                heapq.heappush(heap, (nd, nxt))
    return dist

Trace it with edges 0 to 1 costing 4, 0 to 2 costing 1, and 2 to 1 costing 2. From 0, node 1 gets 4 and node 2 gets 1. Node 2 comes off the heap next and improves node 1 to 3. The entry (3, 1) is processed, and the old entry (4, 1) is later skipped as stale. Final distances: 0, 3 and 1.

With a binary heap this runs in O((V + E) log V). Two limits are worth stating unprompted: negative edge weights break it (use Bellman-Ford instead), and if every edge costs the same, plain BFS is simpler and faster.

Union-find: groups that merge over time

Union-find keeps a forest where each group points to a representative. find returns a node's representative; union merges two groups. With path compression and union by size, each operation costs nearly constant amortized time.

class UnionFind:
    def __init__(self, n: int) -> None:
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False  # already connected: this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True

Use it when edges arrive over time and you need connectivity answers in between, or to find the edge that creates a cycle in an undirected graph. For a one-off component count on a fixed graph, the DFS above is just as good.

What the interviewer hears: weak and strong

Prompt: "Given flights as (from, to, price), return the cheapest price from A to B."

A weak answer hears "shortest path", writes a BFS, and returns the price of the route with the fewest flights. With a direct flight from A to B at 500, and flights A to C at 100 and C to B at 100, it returns 500. The right answer is 200. The code was clean; the model was wrong, and that costs both problem solving and correctness.

A strong answer models first, out loud: "Airports are nodes. Each flight is a directed edge weighted by price. Prices are never negative, so Dijkstra applies; BFS would only be right if every flight cost the same." Then the code from above, the complexity, O((V + E) log V), and three tests: B unreachable (return -1, or whatever the interviewer asks for), A equal to B (0), and the two-hop route that beats the direct one. Naming that last case shows the interviewer you know exactly where BFS would have failed.

When a candidate picks the wrong algorithm, the interviewer's nudge is usually a counterexample in disguise: "What if the direct flight were more expensive?" Treat it as one, and re-check your model rather than patching the code.

Follow-ups to expect

  • "What if the graph is too big for memory?" Explore lazily: generate neighbors on demand (as with the grid), and consider bidirectional BFS, which searches from both ends and meets in the middle.

  • "Can there be cycles?" Always ask. In an undirected graph, the visited set handles them; in a dependency graph, a cycle means no valid answer.

  • "What if edge costs are only 0 or 1?" A deque-based BFS (0 costs go to the front, 1 costs to the back) beats Dijkstra.

  • "Return the path, not just the length." Record each node's parent when you first reach it, then walk back from the target.

What changes with seniority

A junior candidate is expected to model the problem as a graph with help and run a correct BFS or DFS. A mid-level candidate picks the algorithm from the cue, handles disconnected graphs and cycles, and states O(V + E). A senior candidate justifies the choice against alternatives (BFS versus Dijkstra, DFS versus union-find), names the limits (negative weights, recursion depth), and adapts to follow-ups such as returning the path or handling a graph that does not fit in memory.

Mistakes that cost points

  • No visited set, or one updated on dequeue. Mark when you enqueue.

  • Using DFS for a shortest path. DFS finds a path, not the shortest one.

  • Forgetting isolated nodes. Loop over all nodes, not just the edges.

  • Recursive DFS on a huge grid. Use an explicit stack.

  • Dijkstra with negative weights, or without the stale-entry check. The first is wrong; the second is slow.

Practice it

A 15-minute drill:

  1. Take the flights example and add a limit: the cheapest price from A to B using at most k flights. Explain why Dijkstra's stale-entry check can now throw away the route you need, and what you would add to each heap entry to fix it.

  2. Change shortest_path into a multi-source version that returns the distance from every open cell to the nearest cell marked E.

  3. Trace topo_order on four tasks with prerequisites (0, 2), (1, 2) and (2, 3), and confirm that 0, 1, 2, 3 is one valid answer.

Then rehearse modeling out loud (nodes, edges, algorithm, complexity, tests) in a full coding interview such as Two Sum.

Previous: Trees, where the same traversals run without cycles. Dijkstra relies on the heap from Heaps and Top K.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Backtracking: Searching Every Option Without Getting Lost

    Spot 'list every answer' problems, apply one choose, explore, unchoose template to subsets, permutations, combinations and constraint puzzles, prune early, and state the exponential cost honestly.

    9 min read

  • Dynamic Programming: From Recursion to a Table

    Recognize a dynamic programming problem, apply a five-step recipe (state, recurrence, base case, order, answer), move from memoization to a table and cut its space, and explain the solution out loud.

    9 min read

  • Intervals and Greedy: Sort First, Then Decide Once

    Merge, insert and count overlapping intervals with a sort-then-sweep template, justify a greedy rule with the exchange argument, and recognize when greedy fails and dynamic programming is needed.

    9 min read

  • Two Pointers

    Recognize when sorted input, in-place edits or a linked list call for two pointers, then apply the opposite-ends, reader-writer and fast-slow shapes and say why each pointer move is safe.

    8 min read