Sub topic 13
From Two Colours to Three: Where It Gets Hard
Earlier chapters showed that you can decide whether a graph is two-colourable in O(V + E) time, and that you can return an odd cycle as proof when it is not. Adding a third colour looks like a small change. It is not small. Deciding whether a graph can be properly coloured with three colours is NP-complete, so no polynomial-time algorithm for it is known, and finding one would prove P = NP.
This chapter assumes you have read the BFS two-colouring and odd-cycle chapters. You should know what NP-completeness means in outline: a problem in NP whose solutions are easy to check, and to which every other NP problem reduces. You should also be comfortable reading recursive Python.
Why Two Colours Are Easy: Forced Moves
Look again at the key line in the BFS two-colouring:
colour[v] = 1 - colour[u]Once u has a colour, its uncoloured neighbour v has exactly one legal colour. The algorithm never chooses anything except the colour of the first vertex in each component, and swapping the two colours handles that choice. After that, every colour is forced. A conflict found later therefore means no colouring exists. It cannot mean that an earlier choice was wrong, because no earlier choice was made.
Algebra gives another way to see this. With colours 0 and 1, the edge constraint "u and v differ" is the linear equation
xu + xv = 1 (mod 2).
Two-colouring is then a system of linear equations over the integers mod 2. Propagating the constraints, or Gaussian elimination, solves such systems in polynomial time.
With three colours, the rule "u and v differ" leaves v with two legal colours once u is coloured. The constraint is a relation, not a function, and it is not a linear equation over the integers mod 3. Choices stop being forced. A conflict deep in the search can come from a choice made much earlier, so the algorithm has to backtrack.
The same split separates 2-SAT from 3-SAT. In 2-SAT each clause has two literals, so setting one literal false forces the other true, and implication propagation solves it in linear time. In 3-SAT, setting one literal false still leaves two ways to satisfy the clause, and the problem is NP-complete. The parallel is close, and the hardness proof below uses it directly.
| Property | 2-colouring | 3-colouring |
|---|---|---|
| Legal colours for a neighbour of a coloured vertex | 1 | 2 |
| Constraint type | Linear equation mod 2 | Inequality, not linear |
| Exact algorithm | BFS/DFS, O(V + E) | Exponential in the worst case |
| Certificate of "no" | Odd cycle, short and easy to check | No short certificate known (that would imply NP = co-NP) |
| Complexity class | P | NP-complete |
What NP-Completeness Requires
Proving 3-colouring NP-complete takes two steps.
It is in NP. Given a proposed colouring, you can check it in O(V + E) time by looking at every edge once:
def is_proper(n, adj, colour, k):
"""Check that colour is a proper k-colouring of the graph."""
if len(colour) != n or any(not (0 <= c < k) for c in colour):
return False
return all(colour[u] != colour[v] for u in range(n) for v in adj[u])
c5 = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]
print(is_proper(5, c5, [0, 1, 0, 1, 2], 3)) # True
print(is_proper(5, c5, [0, 1, 0, 1, 0], 3)) # False: edge 4-0It is NP-hard. Every instance of a known NP-complete problem, here 3-SAT, can be turned in polynomial time into a graph that is 3-colourable exactly when the formula is satisfiable. Karp included graph colouring in his 1972 list of 21 NP-complete problems. The 3-SAT reduction below is the version usually taught.
Sketch of the Reduction from 3-SAT
The construction uses gadgets: small subgraphs whose possible colourings mimic logic.
- Palette triangle. Add a triangle on three vertices named T, F and B (true, false, base). Every proper 3-colouring gives them three different colours, so you can read those colours as "true", "false" and "neither".
- Variable gadgets. For each variable x, add the vertices x and ¬x, and join them to each other and to B. They form a triangle with B, so one of them gets T's colour and the other gets F's colour. That is a truth assignment.
- Clause gadgets. A two-input OR gadget on inputs a and b is a triangle p, q, o in which p is joined to a and q is joined to b. If a and b are both coloured F, then p and q must use T and B, which forces o to be F. If either input is T, the gadget can be coloured so that o is not F. For a clause (a ∨ b ∨ c), chain two OR gadgets: OR(a, b) feeds into OR(·, c). Then join the final output to F and B, which forces it to be T.
A clause gadget can be coloured only if at least one of its literals is T. The whole graph is 3-colourable exactly when some assignment satisfies every clause. The graph has O(number of variables + number of clauses) vertices, so the reduction runs in polynomial time.
Hardness carries upward. To reduce 3-colouring to k-colouring, add k − 3 new vertices joined to every vertex and to each other. Those vertices use up k − 3 colours, and the original graph is left with exactly three. So k-colouring is NP-complete for every k ≥ 3. Bipartiteness is the only nontrivial case that is easy.
What Exact Search Looks Like
Without propagation that settles everything, an exact solver has to search. Here is a straightforward backtracking k-colourer. It colours vertices in order of decreasing degree, which is a common heuristic because constrained vertices fail early.
import sys
def k_colour(n, adj, k):
"""Return a proper k-colouring as a list, or None if none exists."""
sys.setrecursionlimit(max(1000, 2 * n + 100))
colour = [-1] * n
order = sorted(range(n), key=lambda v: -len(adj[v]))
def place(i):
if i == n:
return True
u = order[i]
for c in range(k):
if all(colour[v] != c for v in adj[u]):
colour[u] = c
if place(i + 1):
return True
colour[u] = -1 # undo and try the next colour
return False
return colour if place(0) else None
c5 = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]
k4 = [[1, 2, 3], [0, 2, 3], [0, 1, 3], [0, 1, 2]]
print(k_colour(5, c5, 2)) # None: odd cycle
print(k_colour(5, c5, 3)) # [0, 1, 0, 1, 2]
print(k_colour(4, k4, 3)) # None: K4 needs four coloursThe line colour[u] = -1 is the step BFS two-colouring never needs. It undoes a choice that might have been fine on its own but led to a dead end later. In the worst case this search explores up to k^V partial assignments. Better exact algorithms exist. For 3-colouring, Beigel and Eppstein's algorithm runs in about O(1.3289^V), which beats 3^V by a wide margin but is still exponential.
Easy Special Cases and Where Hardness Persists
NP-completeness describes the worst case over all graphs. Many structured graph classes are easy, and recognising one can save you from an exponential search.
| Graph class | 3-colouring status |
|---|---|
| Bipartite | Always 2-colourable; BFS decides it |
| Maximum degree ≤ 3 | Polynomial. By Brooks' theorem a connected graph is 3-colourable unless it is K4 (an odd cycle needs exactly 3, which is fine) |
| Maximum degree 4 | Still NP-complete |
| Planar | Always 4-colourable (Four Colour Theorem), but deciding 3-colourability is NP-complete |
| Chordal, interval, and more generally perfect graphs | Chromatic number computable in polynomial time |
| Trees and forests | Bipartite, so 2 colours suffice |
The planar row is a common surprise. "Always colourable with four colours" and "deciding three colours is easy" are separate claims. The first is a guarantee. The second is a decision problem, and it stays hard.
Approximation does not help much either. For general graphs, approximating the chromatic number within a factor of V^(1−ε), for any ε > 0, is NP-hard (Zuckerman, 2007). Even when you know a graph is 3-colourable, the best known polynomial-time algorithms can only promise a colouring with a polynomial number of colours, roughly V^0.2.
Decision Criteria in Practice
When a problem looks like colouring, ask how many groups you need:
- Two groups (two shifts, two teams, two sides of a split): model it as bipartiteness. Use BFS or DFS, return an odd cycle when it fails, and use parity union-find if constraints arrive one at a time. Expect linear time.
- Three or more groups, small graph (up to a few dozen vertices, or a structured instance): backtracking with good vertex ordering, or a SAT or constraint solver, is usually fast enough.
- Three or more groups, large graph, any valid answer acceptable: use heuristics such as greedy colouring in largest-degree-first order, or DSatur. They are fast but may use more colours than necessary, and they never prove that fewer colours are impossible.
- Check your graph class first. Interval graphs (for example, timetabling non-overlapping time slots) and other perfect graphs have exact polynomial algorithms.
Exercise
The rule "u and v get different colours" forces exactly one colour for v once u is coloured, but only when there are two colours. Using this, explain in two or three sentences why the BFS algorithm is correct for two colours, and why the same algorithm with three colours (always picking the smallest legal colour) can report failure on a 3-colourable graph.
Show answer
With two colours, every colour after the first vertex in each component is forced, so the algorithm makes no real choices. A conflict therefore proves that no colouring exists. With three colours, each neighbour has two legal options, and picking the smallest is an arbitrary choice. A later conflict may come from that choice and not from the graph itself, so failure proves nothing unless the algorithm backtracks and tries the alternatives.
Exercise
Show that 4-colouring is NP-complete, assuming 3-colouring is. Describe the reduction and argue both directions.
Show answer
Given a graph G, build G' by adding one new vertex w joined to every vertex of G. If G has a 3-colouring, give w the fourth colour, and you get a 4-colouring of G'. If G' has a 4-colouring, w's colour appears on no vertex of G, because w is adjacent to all of them. So G uses at most three colours, which is a 3-colouring. The construction adds V edges, so it runs in polynomial time, and 4-colouring is in NP because a colouring can be checked in O(V + E) time.
Exercise
A colleague says: "Planar graphs are always 4-colourable, so deciding whether a planar graph is 3-colourable must be easy." Is that right? What about a graph whose maximum degree is 3?
Show answer
No. A guarantee of four colours says nothing about the decision problem for three, and 3-colouring planar graphs is NP-complete (it stays hard even for planar graphs of maximum degree 4). For maximum degree 3 the decision is easy. By Brooks' theorem, every connected graph with maximum degree at most 3 is 3-colourable unless it is K4, so you only need to check each component for K4 (and you can then find a colouring in polynomial time).
Exercise
Run k_colour on K4 (the complete graph on 4 vertices) with k = 3 and k = 4. Before running it, predict the outputs, and estimate how many times place is called in the k = 3 case.
Show answer
With k = 3 the result is None. With k = 4 the result is [0, 1, 2, 3]. For k = 3, the first three vertices are forced into distinct colours along each branch, and the fourth has no legal colour. The search tries all 3 × 2 × 1 = 6 orderings of colours on the first three vertices, so place is called 1 + 3 + 6 + 6 = 16 times, with each call at the fourth level failing immediately. You can confirm this by adding a counter.