Sub topic 1
Representing Graphs with Adjacency Lists
Every algorithm in this tutorial reads a graph in the same format: a vertex count n and an adjacency list adj. This chapter fixes that format, shows how to build it from raw edge data, and lists the input mistakes that most often break a bipartiteness check before the algorithm even runs.
Prerequisites
This chapter assumes you already know:
- Basic graph terms: vertex, edge, path, cycle, and the difference between directed and undirected graphs.
- How breadth-first search (BFS) and depth-first search (DFS) visit vertices.
- Big-O notation.
- Python lists, loops and tuples.
The working model
An adjacency list stores, for each vertex, the list of vertices it shares an edge with. In this tutorial the vertices are the integers 0 to n - 1, and adj[u] is a Python list of the neighbours of u.
Bipartiteness is a property of undirected graphs, so every edge {u, v} appears twice: v goes in adj[u] and u goes in adj[v]. The two-colouring algorithms in later chapters depend on this symmetry. When they look at a vertex, they expect to see every edge that touches it.
In Python, the square above is:
square = [[1, 3], [0, 2], [1, 3], [2, 0]]Building the list from an edge list
Problem inputs usually arrive as a list of edges. The function below converts them, and it also handles the cleanup that real data tends to need.
def build_adj(n, edges, one_indexed=False):
"""Build an undirected adjacency list from (u, v) pairs."""
adj = [[] for _ in range(n)]
seen = set()
for u, v in edges:
if one_indexed:
u, v = u - 1, v - 1
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"edge ({u}, {v}) out of range for n={n}")
key = (min(u, v), max(u, v))
if key in seen:
continue # skip duplicate edges
seen.add(key)
adj[u].append(v)
if u != v:
adj[v].append(u) # undirected: store both directions
return adj
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (1, 0)]
print(build_adj(4, edges))
# [[1, 3], [0, 2], [1, 3], [2, 0]]The repeated edge (1, 0) is dropped, so the result matches square exactly.
Why adjacency lists
| Representation | Memory | List neighbours of u | Test edge (u, v) |
|---|---|---|---|
| Adjacency list | O(V + E) | O(deg u) | O(deg u) |
| Adjacency matrix | O(V²) | O(V) | O(1) |
| Edge list | O(E) | O(E) | O(E) |
Two-colouring visits each vertex once and scans each of its neighbours once. It never asks whether one particular edge exists. The adjacency list makes that scan cheap, and it is what lets the algorithms later in the tutorial run in O(V + E) time. A matrix would push the cost up to O(V²), even for a sparse graph.
Common errors
- Missing reverse edge. If you only append
vtoadj[u], the graph becomes directed by accident. A traversal can then miss vertices, or never examine the edge that would reveal a conflict. - Off-by-one indexing. Many datasets number vertices from 1. If you forget to shift them, you get an
IndexError, or vertex0becomes a phantom isolated vertex. - Self-loops. An edge
(u, u)makes a graph non-bipartite straight away, becauseuwould have to differ in colour from itself. Keep it in the list rather than silently discarding it, so the colouring code can see it and reject the graph. - Isolated vertices left out. If you size
adjfrom the edges instead of fromn, any vertex with no edges disappears. A later chapter colours every component, and that includes single vertices. - Shared inner lists.
[[]] * ncreatesnreferences to one list. Use[[] for _ in range(n)].
Exercise
Using buildadj, what is the adjacency list for n = 3 with oneindexed=True and edges [(1, 2), (2, 3), (3, 1)]? Is any vertex missing a neighbour?
Show answer
[[1, 2], [0, 2], [1, 0]]. After shifting to 0-indexed, the edges are (0, 1), (1, 2) and (2, 0). Each vertex appears in both of its neighbours' lists, so no neighbour is missing. This is the triangle used in later chapters.
Exercise
A graph has n = 5 and edges [(0, 1), (1, 2)]. A student builds adj with one list per vertex that appears in some edge. What goes wrong when that graph is later checked vertex by vertex?
Show answer
Vertices 3 and 4 have no edges, so they never get a list. Any code that loops over range(n) and reads adj[3] raises an IndexError. Sizing adj from n gives isolated vertices an empty list, and the colouring code can then colour them freely.