Sub topic 7
Why Two-Colouring Runs in Linear Time
This chapter assumes you know Big-O notation, can read the BFS two-colouring function from the earlier chapter, and know how adjacency lists store a graph. The goal here is to show why that function runs in O(V + E) time, where V is the number of vertices and E the number of edges. You will also see the small implementation choices that quietly make it slower.
Counting the work instead of the loops
The BFS two-colouring code has three nested loops: one over start vertices, one while over the queue, and one for over neighbours. If you multiply the loop bounds you get O(V · V · V), which is far too pessimistic. A better approach is to charge each unit of work to a specific vertex or edge and show that nothing gets charged too often.
Two facts do the accounting:
- Each vertex enters the queue at most once. A vertex is pushed only when its colour is
-1, and it gets a colour at the moment it is pushed. After that, thecolour[v] == -1test fails for it forever. - Each adjacency list is scanned at most once. A vertex's neighbours are read only when that vertex is popped. Since it is pushed once, it is popped once.
In an undirected graph, every edge appears in two adjacency lists, so the lengths of all lists add up to exactly 2E. Scanning every list once costs O(E). The outer for start in range(n) loop adds O(V) on top, because it looks at every vertex once even when that vertex is already coloured.
| Work item | Charged to | Total cost |
|---|---|---|
| Outer-loop colour check | each vertex | V |
| Queue push and pop | each vertex | 2V |
| Neighbour test inside `for v in adj[u]` | each edge endpoint | 2E |
| Early return on conflict | once | O(1) |
Seeing the counts
You can check the argument by counting pushes and neighbour scans directly. The test graph below has two components, a path on five vertices and a single edge, so V = 7 and E = 5.
from collections import deque
def two_colour_counted(n, adj):
colour = [-1] * n
pushes = 0
scans = 0
for start in range(n):
if colour[start] != -1:
continue
colour[start] = 0
queue = deque([start])
pushes += 1
while queue:
u = queue.popleft()
for v in adj[u]:
scans += 1
if colour[v] == -1:
colour[v] = 1 - colour[u]
queue.append(v)
pushes += 1
elif colour[v] == colour[u]:
return None, pushes, scans
return colour, pushes, scans
n = 7
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (5, 6)]
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
print(two_colour_counted(n, adj)) # ([0, 1, 0, 1, 0, 0, 1], 7, 10)The counts match the analysis: 7 pushes (one per vertex) and 10 scans (2E).
Space usage
The algorithm uses the colour array (V entries) and the queue, which never holds more than V vertices. Extra space is therefore O(V). The adjacency list itself takes O(V + E), but the input already pays for that.
Common ways to lose linear time
- Using
list.pop(0)as the queue. Each pop shifts the whole list, so it costs O(V) per pop and O(V²) in total. Usecollections.dequeandpopleft(). - Using an adjacency matrix. Finding a vertex's neighbours means scanning a whole row of V entries, so the total becomes O(V²) whatever the value of E. This hurts most on sparse graphs.
- Colouring on pop instead of on push. If you mark a vertex only when it leaves the queue, the same vertex can be pushed once by each neighbour. That makes the queue hold O(E) entries and makes the code harder to reason about. Assign the colour when you push.
- Resetting
colourper component. Allocating a fresh array for each start vertex costs O(V) per component, which is O(V²) on a graph with many isolated vertices.
Exercise
A graph has V = 10,000 vertices and E = 20,000 edges. Roughly how many neighbour checks does BFS two-colouring do with adjacency lists, and how many with an adjacency matrix?
Show answer
With adjacency lists it does about 2E = 40,000 neighbour checks, plus 10,000 outer-loop checks. With an adjacency matrix, every popped vertex scans a full row of 10,000 entries, so it does about V² = 100,000,000 checks, roughly 2,500 times more.
Exercise
Someone replaces deque with a plain Python list and uses queue.pop(0). The output is still correct. What is the new worst-case running time, and why?
Show answer
O(V² + E). Each pop(0) shifts every remaining element, which costs up to O(V), and there are V pops. The neighbour scans still cost O(E).