Sub topic 7
Why Two-Colouring Runs in Linear Time
This chapter assumes you have read the BFS two-colouring chapter and know the two_colour function from it. You should also be comfortable with Big-O notation and with the adjacency list representation. The goal is to prove that BFS two-colouring runs in O(V + E) time and O(V) extra space. The chapter also covers how that bound depends on choices that are easy to get wrong, and why no correct algorithm can beat it.
What "linear" means for a graph
A graph with V vertices and E edges stored as adjacency lists takes Θ(V + E) memory. There is one list header per vertex and two entries per undirected edge. An algorithm is linear in the input size when its running time is O(V + E). Neither term can be dropped.
- E alone is not enough. A graph with 10⁶ isolated vertices has E = 0, but the algorithm still has to visit and colour every vertex.
- V alone is not enough. A dense graph can have close to V²/2 edges, and every one of them may need checking.
Saying O(V + E) instead of O(V²) or O(VE) is a real claim. It holds only when each vertex and each edge is handled a constant number of times.
Counting the work in BFS two-colouring
Here is the BFS algorithm again, split into the parts that cost time:
- The outer loop over
start in range(n)runs exactly V times. Each iteration either skips a coloured vertex in O(1) or starts a new BFS. - Enqueue and dequeue. A vertex is appended to the queue only at the moment it changes from uncoloured to coloured. Colours never change back to −1, so each vertex enters the queue at most once and leaves it at most once. That makes at most V
popleftcalls in total, across all components. - Adjacency scans. When vertex u is dequeued, the inner loop reads all of
adj[u], which takes deg(u) steps of O(1) each. Since u is dequeued at most once, the total scanning cost is the sum of all degrees.
The handshake lemma gives that sum: in an undirected graph, Σ deg(u) = 2E, because each edge {u, v} shows up once in adj[u] and once in adj[v]. Adding the parts together:
| Part of the algorithm | Times executed | Cost each | Total |
|---|---|---|---|
| Outer loop check | V | O(1) | O(V) |
| Enqueue / dequeue | at most V | O(1) with `deque` | O(V) |
| Neighbour inspection | Σ deg(u) = 2E | O(1) | O(E) |
| Colour array initialisation | 1 | O(V) | O(V) |
| **Overall** | **O(V + E)** |
This is aggregate analysis. It does not bound the cost of each BFS call separately and then multiply. It charges each unit of work to a vertex or to an edge and checks that nothing is charged more than a constant number of times. The same argument covers disconnected graphs: every component's BFS draws on the same budget of V dequeues and 2E scans, so running BFS once per component adds nothing beyond the outer loop.
Checking the count empirically
The argument predicts exact numbers for a bipartite graph, where the algorithm never stops early: V dequeues and 2E neighbour inspections. The script below counts both and compares them with the prediction on random bipartite graphs of growing size.
from collections import deque
import random
def two_colour_counted(n, adj):
"""BFS two-colouring that also counts dequeues and neighbour inspections."""
colour = [-1] * n
pops = 0
scans = 0
for start in range(n):
if colour[start] != -1:
continue
colour[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
pops += 1
for v in adj[u]:
scans += 1
if colour[v] == -1:
colour[v] = 1 - colour[u]
queue.append(v)
elif colour[v] == colour[u]:
return None, pops, scans
return colour, pops, scans
def random_bipartite(n, m, seed=0):
"""m random edges between the first half and the second half of the vertices."""
rng = random.Random(seed)
half = n // 2
adj = [[] for _ in range(n)]
for _ in range(m):
u = rng.randrange(half)
v = rng.randrange(half, n)
adj[u].append(v)
adj[v].append(u)
return adj
for n, m in [(1_000, 5_000), (10_000, 50_000), (100_000, 500_000)]:
adj = random_bipartite(n, m)
colouring, pops, scans = two_colour_counted(n, adj)
print(f"V={n:>7} E={m:>7} pops={pops:>7} scans={scans:>8} "
f"pops==V: {pops == n} scans==2E: {scans == 2 * m}")Every line prints True for both checks. Some vertices end up isolated in these random graphs, and those still count toward pops because the outer loop starts a one-vertex BFS from each of them. If you time the runs, the time per (V + E) unit stays about the same as the input grows by a factor of 100.
Space usage
Apart from the graph itself, the algorithm uses:
- the
colourarray, which is exactly V entries; - the queue, which never holds more than V vertices because each vertex enters it at most once.
That makes the extra space O(V). The adjacency lists take Θ(V + E), but they are the input. If you have to build them from an edge list, that step is also linear:
def build_adj(n, edges):
"""Turn a list of (u, v) pairs into adjacency lists in O(V + E) time."""
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj
print(build_adj(4, [(0, 1), (1, 2), (2, 3), (3, 0)]))
# [[1, 3], [0, 2], [1, 3], [2, 0]]The full pipeline, from raw edge list to colouring, therefore stays O(V + E).
How the bound breaks
The O(V + E) proof relies on two assumptions: dequeuing costs O(1), and listing the neighbours of u costs O(deg(u)). If either one fails, the bound fails with it.
Using a Python list as a queue
list.pop(0) shifts every remaining element, so it costs O(length of list). If a BFS uses queue.pop(0) and the queue grows to Θ(V), as it does on a star graph or a wide grid, the dequeues alone cost Θ(V²). The algorithm is still correct but runs quadratically. collections.deque.popleft() is O(1), which is why the reference code uses it.
Choosing the wrong representation
The neighbour-scan step costs whatever your representation charges to list one vertex's neighbours.
| Representation | Cost to list neighbours of u | Total two-colouring time |
|---|---|---|
| Adjacency list | O(deg(u)) | O(V + E) |
| Adjacency matrix | O(V) per vertex | O(V²) |
| Raw edge list, scanned per vertex | O(E) per vertex | O(V · E) |
| Dict of sets | O(deg(u)) expected | O(V + E) expected |
An adjacency matrix gives O(V²). That is optimal for dense graphs, where E is Θ(V²) anyway, but very wasteful for sparse graphs such as road networks, where E is roughly proportional to V. A raw edge list that you scan in full for every dequeued vertex is worse than both.
Hidden costs in the colour lookup
colour[v] is an O(1) array index when vertices are the integers 0 to n − 1. If vertices are strings or tuples and colours live in a dict, each lookup is O(1) expected, which keeps the bound in expectation. If you store colours in a structure with slower membership tests, such as a list of coloured vertices checked with in, each lookup costs O(V) and the total becomes O(V · E).
Edge cases that stay within the bound
- Empty graph (V = 0). The outer loop does not run and the function returns
[]. This is correct, since an empty graph is trivially bipartite. - Isolated vertices. Each one costs a single outer-loop iteration and a BFS with no neighbours to scan. They receive colour 0.
- Parallel edges. If {u, v} appears k times, it adds k entries to each list. The handshake count becomes 2 × (number of edge entries), so the bound is linear in the size of the input as stored. Duplicate edges never change the answer.
- Self-loops. An edge (u, u) puts u in its own list. When u is scanned,
colour[u] == colour[u]holds and the function returnsNone. A self-loop is a cycle of length 1, which is odd, so this answer is correct and costs O(1) extra. - Early exit. On a non-bipartite graph the function can return after a small part of the input. The worst case is still O(V + E), and the analysis above is an upper bound that covers every run.
Why you cannot do better
O(V + E) is optimal up to constant factors, and two arguments show why.
- Every vertex must be touched. The output assigns a colour to every vertex, so writing it alone takes Ω(V).
- Every edge must be read in the worst case. Suppose an algorithm declares a graph bipartite without inspecting some edge {u, v}. An adversary can build a bipartite graph in which u and v get the same colour in every valid two-colouring, for example as the two ends of an even-length path, and then add the unread edge between them. The new graph has an odd cycle, but the algorithm saw the same input it saw before and gives the same wrong answer. So any correct algorithm needs Ω(E) edge reads on some inputs.
Together these give a Θ(V + E) lower bound, so BFS two-colouring is asymptotically optimal. This sets up the contrast in the final chapter: two colours can be checked in time proportional to reading the graph, while no polynomial-time algorithm is known for three colours.
Exercise
A student implements BFS two-colouring with an adjacency matrix and collections.deque. On a graph with V = 50,000 vertices and E = 100,000 edges it is far slower than expected. Estimate the number of neighbour-inspection steps for the matrix version and for an adjacency list version, and explain the difference.
Show answer
With a matrix, each dequeued vertex scans a full row of V entries, so the total is V × V = 2.5 × 10⁹ steps. With adjacency lists the total is Σ deg(u) = 2E = 200,000 steps. The matrix version does about 12,500 times more work, because it pays for every possible edge rather than every actual edge. For sparse graphs, O(V²) is much larger than O(V + E).
Exercise
Replace queue.popleft() with queue.pop(0) on a plain list and run the algorithm on a star graph: vertex 0 joined to vertices 1 to n − 1. What is the running time, and why?
Show answer
Θ(n²). Vertex 0 is dequeued first and enqueues all n − 1 leaves, so the list then holds n − 1 items. Each later pop(0) shifts all remaining items, costing (n − 2) + (n − 3) + … + 1 = Θ(n²) in total. The neighbour scans still cost only Θ(n), so the queue operations are what make the run quadratic.
Exercise
The graph has V vertices and contains a self-loop at vertex V − 1 and no other edges. How many outer-loop iterations and how many neighbour inspections happen before two_colour returns, and what does it return?
Show answer
Vertices 0 to V − 2 are isolated, so each one takes one outer-loop iteration, gets colour 0, is dequeued, and has no neighbours to scan. On iteration V, vertex V − 1 is coloured 0 and dequeued, and its list contains itself. If the self-loop is stored once, the first inspection finds colour[v] == colour[u] and returns None. That is V outer iterations and 1 neighbour inspection, which is still O(V + E).