Data structure · Graphs and disjoint sets
Graph
Vertices joined by edges, stored as adjacency lists or a matrix. The representation decides how fast you can list neighbours or test an edge.
The derivations, edge cases and exercises are in the lesson Graph representations: edge list, adjacency matrix and adjacency list.
The idea
A graph is a set of vertices and a set of edges between them, directed or undirected, optionally weighted. Trees, grids, dependency lists and road maps are all graphs.
Adjacency lists store each vertex’s neighbours and use O(V + E) memory, ideal for sparse graphs and traversals. An adjacency matrix answers “is there an edge u → v?” in O(1) but costs O(V²) memory. The lessons compare the two in detail.
Representation. Adjacency lists: an array indexed by vertex, each holding that vertex’s neighbours (and weights).
Operations
| Operation | Time | Extra space | Notes |
|---|---|---|---|
| Add edge | O(1) | O(1) amortized | Adjacency list; matrix is O(1) too. |
| List neighbours of v | O(deg v) | O(1) | Matrix: O(V). |
| Edge u → v? | O(deg u) | O(1) | Matrix: O(1). |
| Visit everything (BFS / DFS) | O(V + E) | O(V) | Matrix: O(V²). |
| Memory | — | O(V + E) | Matrix: O(V²). |
Invariants
What stays true before and after every operation.
- In an undirected graph each edge appears in both endpoints’ lists.
- The sum of all list lengths is E (directed) or 2E (undirected).
When to use it
Use it when
- Your data has relationships rather than a sequence or hierarchy: networks, dependencies, maps, state spaces.
- Use lists for sparse graphs (E much smaller than V²) and a matrix for small dense ones.
Avoid it when
- The relationships form a simple sequence or tree; a specialized structure is simpler.
- A matrix for a large sparse graph: memory grows with V² even when E is tiny.
Built-in equivalents
What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.
C#
No graph type in .NET; List<int>[] or Dictionary<T, List<T>> is the usual adjacency list.
Python
No graph type in the standard library; a list of lists or a dict of lists. graphlib offers topological sorting only.
Java
No graph type in java.util; List<List<Integer>> or Map<T, List<T>>.
C++
No graph type in the standard library; std::vector<std::vector<int>> is the usual adjacency list.
Learn more
Lessons
- Graph representations: edge list, adjacency matrix and adjacency list· M23 Graph Fundamentals
- BFS and DFS on graphs: queues, recursion and what each finds· M24 BFS and DFS
Algorithms that use it
Problems, patterns and exercises
- PatternBreadth-first search and level order· O(V + E)
- PatternTopological ordering· O(V + E)
- PatternUnion-find for connectivity· O(α(n)) amortized per operation