Graph Data Structures

Graphs model pairwise relationships using vertices and directed, undirected, or weighted edges, trading off memory and lookup speed between adjacency lists and adjacency matrices.

One-Line Definition

A graph models relationships using vertices (nodes) and edges—which may be directed, undirected, or weighted—with adjacency lists and adjacency matrices offering complementary trade-offs in memory footprint and lookup speed.

Why It Matters

  • Social networks, road routing, web hyperlinks, package dependencies, knowledge graphs, and neural network computation graphs all map naturally to graphs.
  • Foundational algorithms including BFS, DFS, Dijkstra's shortest path, and topological sorting operate directly on graph representations (see k2.algo.bfs and k2.algo.dijkstra).

Usage Boundaries

In an adjacency list, storing each node's neighbors in a list makes edge-existence queries O(deg⁡u)O(\deg u), whereas storing neighbors in a set trades extra memory for O(1)O(1) average edge lookup. Traversing an undirected tree still requires avoiding the immediate parent edge, and Python's graphlib.TopologicalSorter expects a dictionary mapping each node to its set of predecessor dependencies.

How It Works / Diagram

Figure 1

Comparing the two primary storage layouts:

Representation Space Check if (u,v)(u,v) is an edge Iterate over neighbors of uu Best Suited For
Adjacency Matrix O(V2)O(V^2) O(1)O(1) O(V)O(V) Dense graphs, matrix multiplication ops
Adjacency List O(V+E)O(V+E) O(deg⁡u)O(\deg u) O(deg⁡u)O(\deg u) Sparse graphs (the vast majority of real-world graphs)

In any undirected graph, the sum of vertex degrees equals twice the number of edges (the Handshaking Lemma):

∑v∈Vdeg⁡(v)=2∣E∣ \sum_{v \in V} \deg(v) = 2\lvert E\rvert

A Directed Acyclic Graph (DAG) admits a topological ordering—arranging nodes so every prerequisite appears before the tasks that depend on it. Python 3.9+ includes graphlib.TopologicalSorter in the standard library: https://docs.python.org/3/library/graphlib.html

Figure 2

Runnable Example

Building an adjacency list and adjacency matrix, verifying vertex degrees, and running graphlib.TopologicalSorter on an ML pipeline with cycle detection (verified on Python 3.15.0):

# File: examples/15_graph.py
# Graphs: vertices + edges. Representations: adjacency list (default for sparse graphs) vs. adjacency matrix
from collections import defaultdict

edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("D", "E")]
adj = defaultdict(list)
for u, v in edges:            # Undirected graph: insert both directions
    adj[u].append(v); adj[v].append(u)
print("Adjacency list:", dict(adj))

nodes = sorted(adj)
idx = {n: i for i, n in enumerate(nodes)}
mat = [[0] * len(nodes) for _ in nodes]
for u, v in edges: mat[idx[u]][idx[v]] = mat[idx[v]][idx[u]] = 1
print("Adjacency matrix:")
print("   " + " ".join(nodes))
for n, row in zip(nodes, mat): print(f"{n}  " + " ".join(map(str, row)))
print("Node degrees:", {n: len(adj[n]) for n in nodes})

# Directed Acyclic Graph (DAG) + topological sort: task pipelines, package resolvers, and autograd graphs
from graphlib import TopologicalSorter
deps = {"train": {"tokenize", "download"}, "tokenize": {"download"}, "eval": {"train"}, "report": {"eval", "train"}}
print("Topological execution order:", list(TopologicalSorter(deps).static_order()))
from graphlib import CycleError
try: list(TopologicalSorter({"a": {"b"}, "b": {"a"}}).static_order())
except CycleError as e: print("Cycle detected:", e.args[1])

# Memory footprint comparison for n vertices and m edges
n, m = 10_000, 50_000
print(f"n={n}, m={m}: adjacency matrix needs {n*n:,} cells; adjacency list needs ~{2*m:,} entries")

Recorded output:

Adjacency list: {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C', 'E'], 'E': ['D']}
Adjacency matrix:
   A B C D E
A  0 1 1 0 0
B  1 0 0 1 0
C  1 0 0 1 0
D  0 1 1 0 1
E  0 0 0 1 0
Node degrees: {'A': 2, 'B': 2, 'C': 2, 'D': 3, 'E': 1}
Topological execution order: ['download', 'tokenize', 'train', 'eval', 'report']
Cycle detected: ['a', 'b', 'a']
n=10000, m=50000: adjacency matrix needs 100,000,000 cells; adjacency list needs ~100,000 entries

Notice that the sum of degrees (2+2+2+3+1=10=2×52+2+2+3+1 = 10 = 2 \times 5 edges) confirms the Handshaking Lemma, and on a sparse graph with 10,000 nodes and 50,000 edges, an adjacency matrix allocates 100 million cells compared to roughly 100,000 entries in an adjacency list.

Common Misconceptions

  • Using a dense adjacency matrix for a large sparse graph: O(V2)O(V^2) memory blows up rapidly as vertex count grows.
  • Forgetting a visited set during graph traversal: Any cycle in the graph will cause an infinite loop (and even on an undirected tree, you must avoid stepping immediately back to the parent node).
  • Attempting topological sort on a graph with cycles: No valid linear dependency order exists when a cycle is present; graphlib raises CycleError.
  • Inserting only one direction for an undirected edge: Leads to asymmetric reachability bugs.

Connection to AI Development

  • Autograd computation graphs: PyTorch builds a dynamic DAG of tensor operations during the forward pass and traverses it in reverse topological order during backward() to apply the chain rule (see k2.ml.pytorch).
  • Agent workflow orchestration: Frameworks such as LangGraph model multi-step agent loops, branching tool calls, and human-in-the-loop checkpoints explicitly as state graphs: https://langchain-ai.github.io/langgraph/
  • GraphRAG and knowledge graphs: Extracting entities and relational edges into a graph structure augments vector retrieval on multi-hop questions: https://github.com/microsoft/graphrag
  • HNSW vector indexing: Hierarchical Navigable Small World (HNSW) indexes organize embedding vectors into multi-layer proximity graphs for fast approximate nearest-neighbor search: https://arxiv.org/abs/1603.09320
  • Graph Neural Networks (GNNs): Perform message passing across adjacency matrices (see k2.math.matrix).

Further Reading

Comprehension Check

In graphlib.TopologicalSorter({"A": {"B"}}), does "A": {"B"} mean a directed edge from A to B (A precedes B)?

Reference answer: No—in TopologicalSorter, "A": {"B"} declares that node A depends on predecessor B, so B will be output before A. Always check whether a library's dictionary format maps a node to its outgoing neighbors or its incoming prerequisites.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 15_graph.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram