Skip to contentKEEP THE CRAFTTHE SANCTUARY

Graph

A graph models arbitrary relationships, including cycles and converging paths. Define vertices, direction and duplicate policy before storage, then mark discovery once so traversal counts reachable nodes rather than repeated paths.

9 practice exercises14 interview problems

Recognize it when Entities connect through arbitrary edges rather than one-parent hierarchy.

Checking your account…

Graph Code Labs

Mental Model

A graph separates entities (vertices) from relationships (edges). Unlike a tree, a vertex may have multiple incoming paths, and cycles may return to already discovered state. Direction, weight, parallel edges, and self-loops are contract decisions, not implementation details.

Vertices, Edges, and Direction

For an undirected edge, record both directions; for a directed edge, record only source to target. Degree, reachability, and cycle meaning change with direction. Normalize duplicate-edge policy before building storage so traversal and complexity claims match the logical graph.

Choose an Adjacency Representation

An adjacency list uses O(V + E) space and enumerates actual neighbors efficiently. An adjacency matrix uses O(V squared) space but tests a particular edge in O(1). Compare density and query type rather than choosing by habit. Sets deduplicate neighbors; lists preserve repeated edges and input order.

Build Two Graph Representations

Reference
def build_graph_representations(node_count, edges):
    adjacency = [set() for _ in range(node_count)]
    matrix = [[0 for _ in range(node_count)] for _ in range(node_count)]
    for left, right in edges:
        adjacency[left].add(right)
        adjacency[right].add(left)
        matrix[left][right] = 1
        matrix[right][left] = 1
    return [[sorted(neighbors) for neighbors in adjacency], matrix]
Practice

Implement build_graph_representations(node_count, edges). Deduplicate undirected edges and return sorted adjacency lists plus an adjacency matrix. node_count is a nonnegative integer; every edge endpoint satisfies 0 <= endpoint < node_count.

Public tests

  • Verify matching list and matrix graphs

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

Build Two Graph Representations

def build_graph_representations(node_count, edges):
    adjacency = [set() for _ in range(node_count)]
    matrix = [[0 for _ in range(node_count)] for _ in range(node_count)]
    for left, right in edges:
        adjacency[left].add(right)
        adjacency[right].add(left)
        matrix[left][right] = 1
        matrix[right][left] = 1
    return [[sorted(neighbors) for neighbors in adjacency], matrix]

Traverse with Explicit Visited State

DFS and BFS need visited state because a graph can contain cycles and converging paths. Mark when an item is discovered to prevent duplicate frontier entries. To find components, begin a traversal from each still-unvisited vertex; one traversal consumes exactly one connected component.

Measure Connected Components

Reference
def component_sizes(node_count, edges):
    adjacency = [[] for _ in range(node_count)]
    for left, right in edges:
        adjacency[left].append(right)
        adjacency[right].append(left)
    visited = set()
    sizes = []
    for start in range(node_count):
        if start in visited:
            continue
        visited.add(start)
        stack = [start]
        size = 0
        while stack:
            node = stack.pop()
            size += 1
            for neighbor in adjacency[node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    stack.append(neighbor)
        sizes.append(size)
    return sizes
Practice

Implement component_sizes(node_count, edges). Include isolated vertices and return undirected component sizes in increasing start-vertex order. node_count is a nonnegative integer; every edge endpoint satisfies 0 <= endpoint < node_count.

Public tests

  • Verify cycles and isolated vertices

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

Measure Connected Components

def component_sizes(node_count, edges):
    adjacency = [[] for _ in range(node_count)]
    for left, right in edges:
        adjacency[left].append(right)
        adjacency[right].append(left)
    visited = set()
    sizes = []
    for start in range(node_count):
        if start in visited:
            continue
        visited.add(start)
        stack = [start]
        size = 0
        while stack:
            node = stack.pop()
            size += 1
            for neighbor in adjacency[node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    stack.append(neighbor)
        sizes.append(size)
    return sizes

Trace a Connected Region and Isolated Vertices

The component Lab receives five declared vertices but only a three-node chain of edges. It must return two additional one-node components for vertices 3 and 4. Discovery is recorded before each push.

print(component_sizes(5, [(0, 1), (1, 2)])) followed by print(component_sizes(0, []))

Step Executed statement State Why
1 adjacency[left].append(right); adjacency[right].append(left) after build loop: adjacency = [[1], [0, 2], [1], [], []] All five slots exist, including isolated vertices.
2 visited.add(start); stack = [start]; size = 0 start = 0; visited = {0}; stack = [0] The first component begins with one discovered node.
3 node = stack.pop(); size += 1; visited.add(neighbor); stack.append(neighbor) after node 0: size = 1; visited = {0, 1}; stack = [1] Marking node 1 now prevents another path from rescheduling it.
4 node = stack.pop(); size += 1; visited.add(neighbor); stack.append(neighbor) after node 1: size = 2; visited = {0, 1, 2}; stack = [2] The parent 0 is skipped while new neighbor 2 enters once.
5 node = stack.pop(); size += 1; sizes.append(size) after node 2: sizes = [3]; starts 1 and 2 skipped The stack empties only after the complete region is processed.
6 visited.add(start); stack = [start]; size = 0; node = stack.pop(); size += 1; sizes.append(size) starts 3 and 4 each yield size 1; result = [3, 1, 1] An empty neighbor list still represents a valid one-node component.
Print Output
1 [3, 1, 1]
2 []

The outer start loop determines component order and preserves isolated vertices. Within a component, visited prevents revisiting an undirected parent or a converging route; the stack controls processing order rather than membership.

The deque reference(opens in a new tab) supports the BFS frontier; a list supports iterative DFS as a stack. Both traversals are O(V + E) with adjacency lists because each vertex and stored edge is examined a bounded number of times.

Choose Graph or Grid or Tree

Choose a graph for arbitrary relationships, multiple paths, cycles, or dependencies. Choose an implicit grid when neighbors derive from coordinates instead of stored edges. Choose a rooted tree when every non-root node has one parent and there is a unique root path; then parent state can replace a general visited set. Compare BFS, DFS, topological order, and shortest-path algorithms only after the edge contract is known.

Graph Discovery and Edge Model Mistakes

  • Adding only one direction for an undirected edge loses reachability.
  • Marking visited at removal permits duplicate enqueues and inflated work.
  • Omitting isolated vertices because they never appear in the edge list loses components.
  • Using a V×V matrix for a sparse graph wastes memory.
  • Treating any repeated vertex as a directed-cycle proof ignores active versus completed state.

Explain It in an Interview

State V, E, direction, weight, and duplicate policy before coding. Define what visited means and when it changes. Give O(V + E) for adjacency-list traversal, noting that undirected edges are stored twice, and distinguish frontier space from representation space.

Build Graph Representations(opens in a new tab) forces a storage decision. Course Schedule(opens in a new tab) adds direction and cycle detection to model prerequisites.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Build both representationsO(V * V + E + sum(d * log(d + 1)))O(V * V + E * V + sum(d * log(d + 1)))d is each distinct neighbor count; sorting is charged per vertex. Average uses ordinary hashing; worst permits collision-heavy set insertion.
Measure componentsO(V + E)O((V + E) * V)Includes adjacency, seen/frontier and output. Average uses ordinary integer hashing; collision-heavy seen operations can degrade it.

Space

O(V * V + E) for build both representations; O(V + E) for measure components.

Assumptions

  • d is each distinct neighbor count; sorting is charged per vertex. Average uses ordinary hashing; worst permits collision-heavy set insertion.
  • Includes adjacency, seen/frontier and output. Average uses ordinary integer hashing; collision-heavy seen operations can degrade it.

Invariants Worth Saying Aloud

  1. An undirected logical edge is stored in both directions.
  2. Every declared vertex exists even when no edge mentions it.
  3. Mark a vertex when scheduling it so converging paths cannot schedule it twice.

When To Use Or Avoid Graph

Use It When

  • Choose a graph for arbitrary relationships and select traversal from the required property.
  • Keep representation policy separate from seen/frontier state.

Choose Another Tool When

  • Use an implicit grid when neighbors derive from local coordinates.
  • Use tree parent checks only when acyclicity and unique paths are guaranteed.

Common Pitfalls

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

Recording an undirected edge only once

A one-way insertion loses the reverse reachability promised by an undirected graph.

Prevent it: Insert both endpoint directions under an undirected contract.

Avoid

adjacency[left].append(right)

Use instead

adjacency[left].append(right)
adjacency[right].append(left)

Deferring visited marking until after scheduling

Repeated neighbors can add the same pending vertex twice before processing begins.

Prevent it: Mark each newly discovered neighbor before pushing it.

Avoid

for neighbor in neighbors:
    if neighbor not in seen:
        frontier.append(neighbor)

Use instead

for neighbor in neighbors:
    if neighbor not in seen:
        seen.add(neighbor)
        frontier.append(neighbor)

Inferring the vertex universe from edges alone

Isolated vertices never appear in edges and disappear from the model if endpoints define the universe.

Prevent it: Use the declared node count to initialize every vertex.

Avoid

vertices = {node for edge in edges for node in edge}

Use instead

vertices = set(range(node_count))

Reviewed References

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