Learning path

Full curriculum

Full curriculum

Unit content

Graph representations for algorithms

Algorithms need a concrete way to access a graph's vertices and edges.

An adjacency list stores, for each vertex, the vertices reached by its incident edges. For a graph with $|V|$ vertices and $|E|$ edges, it uses

$$O(|V|+|E|)$$

space and is efficient for iterating over neighbors.

An adjacency matrix stores one entry for every possible vertex pair. It uses

$$O(|V|^2)$$

space but can test whether a particular edge exists in constant time.

Sparse graphs usually favor adjacency lists; dense graphs or algorithms needing frequent arbitrary edge queries may favor matrices.

The representation does not change the mathematical graph, but it changes the cost of the operations available to an algorithm.