Sub topic 1
Representing Graphs with Adjacency Lists
Every algorithm in this tutorial reads a graph in the same form: a vertex count n and an adjacency list adj, where adj[u] holds the neighbours of vertex u. The bipartiteness tests in later chapters only work if that structure is built correctly. An edge stored in one direction only, or a vertex outside the expected range, can make a colouring algorithm quietly return a wrong answer. This chapter fixes the representation we will use, shows how to build it from common input formats, and covers the mistakes that most often break graph code.
Prerequisites
This chapter assumes you already know:
- Basic graph terminology: vertices, edges, paths, cycles, and the difference between directed and undirected graphs.
- Big-O notation, enough to compare O(V + E) with O(V²).
- How to read Python, including lists, tuples, dictionaries, and list comprehensions.
Breadth-first search and depth-first search come up in later chapters. You do not need them here.
The Representation We Will Use
An adjacency list stores, for each vertex, the list of vertices it shares an edge with. In Python the usual choice is a list of lists indexed by vertex number:
- Vertices are the integers
0, 1, ..., n - 1. adj[u]is a Python list of the neighbours ofu.- The graph is undirected. Every edge
{u, v}appears twice: once asvinadj[u]and once asuinadj[v].
Bipartiteness is a property of undirected graphs. If your data has directed edges, such as "A follows B", you still store each edge in both directions before testing it. The direction does not matter to the question "can the vertices be split into two groups with every edge crossing between them?"
Here is the 4-cycle used throughout the tutorial, drawn as a graph:
Its adjacency list is [[1, 3], [0, 2], [1, 3], [2, 0]]. Vertex 0 has neighbours 1 and 3, vertex 1 has neighbours 0 and 2, and so on. The graph has four edges and the lists hold eight entries in total. In general the lengths of all the lists add up to exactly 2E.
Building an Adjacency List from an Edge List
Graphs usually arrive as an edge list, a sequence of pairs (u, v). Converting it takes one pass:
def build_adjacency(n, edges):
"""Build an undirected adjacency list for vertices 0..n-1."""
adj = [[] for _ in range(n)]
for u, v in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"edge ({u}, {v}) has an endpoint outside 0..{n - 1}")
adj[u].append(v)
adj[v].append(u)
return adj
square_edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
triangle_edges = [(0, 1), (1, 2), (2, 0)]
square = build_adjacency(4, square_edges)
triangle = build_adjacency(3, triangle_edges)
print(square) # [[1, 3], [0, 2], [1, 3], [2, 0]]
print(triangle) # [[1, 2], [0, 2], [1, 0]]The two append calls are what make the graph undirected. The range check turns a bad input into an immediate error. Without it you get an IndexError deep inside a search, or no error at all: a negative index such as -1 is valid in Python and silently refers to the last vertex.
Building the list takes O(V + E) time. Creating n empty lists costs O(V), and each edge does a constant amount of work. Memory is also O(V + E). This matches the running time of the colouring algorithms later on, so building the graph never becomes the bottleneck.
Order of neighbours
The order inside each adj[u] depends on the order of the input edges. In the triangle above, adj[2] is [1, 0] rather than [0, 1]. Correctness never depends on this order. It does change which valid colouring a search returns and which odd cycle it reports, so tests should check properties of the output (every edge joins different colours) and not compare it against one exact list.
Common Mistakes
Shared inner lists
The most common Python-specific bug is creating the outer list with multiplication:
bad = [[]] * 3
bad[0].append(1)
print(bad) # [[1], [1], [1]]
good = [[] for _ in range(3)]
good[0].append(1)
print(good) # [[1], [], []][[]] * 3 makes three references to the same list object, so every vertex ends up with every edge. The comprehension creates a separate list for each vertex.
Storing each edge only once
If you write only adj[u].append(v), the structure describes a directed graph. A search started at v cannot see the edge back to u. A two-colouring routine might never compare u and v, and it could accept a graph that contains an odd cycle. The test for this bug is symmetry: v in adj[u] must hold exactly when u in adj[v].
Off-by-one vertex numbers
Many input formats, including most competitive-programming problems and textbook examples, number vertices from 1. Convert them once, at the boundary where you read the input, and keep everything inside the program 0-indexed. Converting halfway through a program is a common source of bugs.
Self-loops and parallel edges
A self-loop is an edge from a vertex to itself. A parallel edge is a second edge between the same pair of vertices. They affect bipartiteness differently:
| Input feature | Effect on the adjacency list | Effect on bipartiteness |
|---|---|---|
| Self-loop `(u, u)` | `u` appears twice in `adj[u]` | Graph is never bipartite, because `u` would have to differ from itself |
| Parallel edge `(u, v)` twice | `v` appears twice in `adj[u]`, `u` twice in `adj[v]` | No effect: the same constraint is stated twice |
| Isolated vertex | `adj[u] == []` | No effect; the vertex can take either colour |
| Vertex absent from all edges but `< n` | Empty list, still present | Must still be coloured, so `n` must be correct |
build_adjacency keeps self-loops on purpose. The colouring code in later chapters then sees u as its own neighbour with the same colour and correctly rejects the graph. If you remove duplicates with sets, check that you keep self-loops when the problem treats them as real edges.
Input Formats You Will Meet
Text with a header line
A typical text format gives n and m (the edge count) and then m pairs, numbered from 1:
def build_adjacency(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"edge ({u}, {v}) has an endpoint outside 0..{n - 1}")
adj[u].append(v)
adj[v].append(u)
return adj
def parse_one_indexed(text):
"""Parse 'n m' followed by m pairs of 1-indexed vertices."""
tokens = text.split()
n, m = int(tokens[0]), int(tokens[1])
if len(tokens) != 2 + 2 * m:
raise ValueError(f"expected {m} edges, got {(len(tokens) - 2) / 2}")
edges = []
for i in range(m):
u = int(tokens[2 + 2 * i]) - 1
v = int(tokens[3 + 2 * i]) - 1
edges.append((u, v))
return n, build_adjacency(n, edges)
data = """4 4
1 2
2 3
3 4
4 1"""
n, adj = parse_one_indexed(data)
print(n, adj) # 4 [[1, 3], [0, 2], [1, 3], [2, 0]]Splitting on whitespace ignores line breaks, so the parser accepts all pairs on one line or one pair per line. The token count check catches truncated files before they produce a graph that is missing edges.
Named vertices
Real data often uses names or IDs instead of integers. Map each label to an index the first time you see it, and keep the reverse mapping so you can report results in the original labels:
def index_labels(edges):
"""Map arbitrary hashable labels to 0..n-1 and build the adjacency list."""
index = {}
for u, v in edges:
for x in (u, v):
if x not in index:
index[x] = len(index)
names = list(index) # dicts keep insertion order
adj = [[] for _ in names]
for u, v in edges:
adj[index[u]].append(index[v])
adj[index[v]].append(index[u])
return names, adj
names, adj = index_labels([("ann", "bob"), ("bob", "cat"), ("cat", "ann")])
print(names) # ['ann', 'bob', 'cat']
print(adj) # [[1, 2], [0, 2], [1, 0]]This version only knows about labels that appear in some edge. If isolated people or items matter, for example because every person must be placed in a group, add them to index before you process the edges.
A dict from label to a set of labels also works, and some libraries use that form. Integer indices make it easy to store colours, parents, and depths in plain lists like colour = [-1] * n, which is the style the rest of this tutorial uses.
Checking a Graph Before You Trust It
When an algorithm gives a surprising answer, check the input first. This helper confirms the two properties every later chapter relies on:
def check_undirected(adj):
"""Raise if adj has out-of-range vertices or a missing reverse edge."""
n = len(adj)
counts = {}
for u, nbrs in enumerate(adj):
for v in nbrs:
if not (0 <= v < n):
raise ValueError(f"adj[{u}] contains out-of-range vertex {v}")
counts[(u, v)] = counts.get((u, v), 0) + 1
for (u, v), c in counts.items():
if counts.get((v, u), 0) != c:
raise ValueError(f"edge {u}->{v} appears {c} times but {v}->{u} does not match")
return True
print(check_undirected([[1, 3], [0, 2], [1, 3], [2, 0]])) # True
try:
check_undirected([[1], [], []])
except ValueError as e:
print(e) # edge 0->1 appears 1 times but 1->0 does not matchCounting ordered pairs also handles parallel edges and self-loops. A self-loop (u, u) adds two entries to the key (u, u), and that key is its own reverse, so the check passes. The check runs in O(V + E) expected time, so you can afford to call it in tests on large graphs.
Adjacency Lists Versus Adjacency Matrices
An adjacency matrix is an n × n table where entry [u][v] records whether the edge exists. It answers "is u adjacent to v?" in constant time, but two-colouring never asks that question. It only asks "what are the neighbours of u?", and the list answers that directly.
| Property | Adjacency list | Adjacency matrix |
|---|---|---|
| Memory | O(V + E) | O(V²) |
| List neighbours of `u` | O(deg(u)) | O(V) |
| Test whether edge `{u, v}` exists | O(deg(u)) | O(1) |
| Two-colouring total time | O(V + E) | O(V²) |
| Good fit | Sparse graphs, traversal | Dense graphs, many edge queries |
For a graph with a million vertices and a few million edges, the list needs a few million entries. The matrix needs a trillion. Every algorithm in the following chapters assumes the list form, and their O(V + E) bounds depend on it.
Exercises
Exercise
An input file contains "3 3" followed by the pairs "1 2", "2 3", "3 3". After parsing with parseoneindexed, what is adj, and what does the last edge imply about whether the graph can be two-coloured?
Show answer
The 0-indexed edges are (0, 1), (1, 2) and (2, 2), so adj is [[1], [0, 2], [1, 2, 2]]. The last edge is a self-loop on vertex 2. It means vertex 2 would need a different colour from itself, so the graph cannot be two-coloured, whatever the other edges are.
Exercise
A colleague builds a graph with adj[u].append(v) only, then runs a two-colouring search that starts at vertex 0. The edges are (1, 0), (1, 2), (2, 0). Explain why the search may wrongly report the graph as two-colourable.
Show answer
With one-directional storage, adj is [[], [0, 2], [0]]. Starting at vertex 0, the search finds no neighbours. If it then restarts at vertex 1, it colours 0 and 2 opposite to 1. Vertex 0 is already coloured and gets checked, but the edge 2-0 is only seen from 2's list if the search processes vertex 2 after both are coloured. Depending on the restart logic, some edges of the triangle are never compared from both ends, and an odd cycle can be missed. Storing both directions guarantees that every edge is examined from at least one endpoint after both endpoints are coloured.
Exercise
A graph has 10,000 vertices and 30,000 edges. Roughly how many neighbour entries does its adjacency list hold, and how many cells would an adjacency matrix need?
Show answer
The adjacency list holds 2E = 60,000 entries plus 10,000 list headers. The matrix needs 10,000 × 10,000 = 100,000,000 cells, which is over a thousand times more storage for this sparse graph.