Learn / Graphs

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

01243
Edges 0-1, 0-4, 1-2, 1-3, 1-4, 2-3, 3-4. Adjacency list: 0: 1 4; 1: 0 2 3 4; 2: 1 3; 3: 1 2 4; 4: 0 1 3.

Vertices, edges, adjacency lists and the other words used here are on the Structures page.

FormMemoryNeighbours of uIs u-v an edge?
edge listO(E)O(E)O(E)
adjacency listO(V + E)O(degree)O(degree)
adjacency matrixO(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

0 of 3 solved

Check yourself

For 5 vertices and 7 undirected edges, how many entries does an adjacency list hold in total?

When is an adjacency matrix a good choice?

In a directed graph, how many times is each triangle counted by checking every ordered triple a → b → c → a?