Representations
A graph is stored as an edge list, an adjacency list (for each vertex, its neighbours) or an adjacency matrix (m[u][v] is 1 when u and v are joined). Adjacency lists use O(V + E) memory and are the usual choice; a matrix answers 'are u and v joined?' in O(1) but uses O(V²).
How to recognise it
- The input is a list of edges that must be turned into something searchable.
- Questions about whether two vertices are joined, or counting small patterns like triangles.
- Choosing between memory and lookup speed.
Three ways to store the same graph
Vertices, edges, adjacency lists and the other words used here are on the Structures page.
| Form | Memory | Neighbours of u | Is u-v an edge? |
|---|---|---|---|
| edge list | O(E) | O(E) | O(E) |
| adjacency list | O(V + E) | O(degree) | O(degree) |
| adjacency matrix | O(V²) | O(V) | O(1) |
adj = [[] for each vertex]
for (u, v) in edges:
adj[u].append(v)
adj[v].append(u) # leave this out for a directed graph
Common mistakes
- Adding only one direction for an undirected edge.
- Building a matrix for a graph with millions of vertices.
Problems
- Create a Graph, print it (implemented code)easyguide ready
- Create a Graph (for practice)easyguide ready
- Number of Triangles in a Directed and Undirected Grapheasyguide ready