Graph coloring
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Graph colouring gives each item a label (colour) so that items that clash never share one, using as few colours as practical. Whenever "these two cannot happen together" is the rule, colours become time slots, rooms or teams.
Practical use cases
- Web app: Exam timetable without clashes. A college portal has subjects and students who take several of them. Two subjects sharing a student are linked, and colouring gives each subject a slot so nobody has two exams at once. The result might fit 40 subjects into 6 slots.
- Web app: Conference session scheduler. A conference site must put talks into rooms and slots, avoiding speakers or popular pairs overlapping. Colouring the clash graph places them into the fewest parallel tracks. Attendees see fewer clashes in their personal agenda, and organisers need fewer rooms because the colours reuse slots wisely.
- Web app: Map or chart colouring feature. A data-visualisation tool colours regions on a map so neighbouring regions never look the same. Greedy colouring needs only a handful of colours and the chart stays readable.
- System: Radio frequencies and compilers. Towers close to each other must use different frequencies, and compilers give variables different CPU registers if they are alive at once. In each case the colours are not really colours but slots, frequencies or registers, and the clash lines tell you what may not share one.
The story: The Exam Timetable Clash
Mrs. Sharma had to make the final exam timetable. Every student takes several subjects, and nobody can write two exams at the same time. Maths and Science had many students in common, so they could not share a slot. Art and Maths had no common students, so they could.
"How many time slots do I need?" she sighed. Mira drew a bubble for each subject and a line between two subjects whenever they clashed. Then she gave each time slot a colour. "Colour every bubble so that connected bubbles never have the same colour. The number of colours is the number of slots!"
They coloured greedily: take the subjects one by one and give each the smallest colour not already used by a neighbour. The result used three colours, and a triangle of mutually clashing subjects proved they could not do better.
This puzzle is graph colouring. The fewest colours needed is the graph's chromatic number. The greedy method is fast and good, but not always perfect: finding the absolute minimum is a famously hard problem, and the order you colour in can change the answer.
How to spot this problem, and where you need it
You have items where certain pairs conflict and cannot share a time, room, frequency or label, and you want to use as few groups as possible.
Signs you need it
- The task says "assign slots so that conflicting items differ" or "minimum number of rooms, colours or days".
- You can list the conflicts as pairs, such as two exams sharing a student or two shifts needing the same person.
- Manual scheduling keeps producing a clash somewhere near the end.
Where to use it in a project
- Timetable, exam, shift and room schedulers in portals and HR systems.
- Map, chart or UI features that need neighbouring things to look different.
The solution
Build a conflict graph with an edge between each clashing pair. Go through nodes one by one, often starting with the one with the most conflicts. For each node, look at the colours used by its neighbours and give it the smallest colour not among them. This greedy method is fast and gives a valid result, though not always the absolute minimum; for tiny inputs use backtracking to find the best.
Payoff: Before: 40 exams spread over 12 slots with manual fixes. After: a valid timetable in 6 slots generated in under a second.
Explain it like I am 8
Colour a map so that countries that touch never get the same colour. You grab the crayons one country at a time and pick the first colour that none of its neighbours is already using.
How it works, step by step
- Draw each item as a node. Draw an edge when two items conflict (must be different).
- Pick a node order (for example by number, or the busiest nodes first).
- For each node, look at the colours of its already coloured neighbours.
- Give the node the smallest colour number that none of them uses.
- The number of colours used is your answer. It is always at most (the largest degree + 1), but sometimes more than the true minimum.
The code in four languages
PHP
<?php
// Greedy graph colouring: smallest colour not used by a neighbour
function colourGraph(array $adj): array {
$n = count($adj);
$colour = array_fill(0, $n, 0); // 0 means "not coloured yet"
for ($u = 0; $u < $n; $u++) {
$taken = [];
foreach ($adj[$u] as $v) {
if ($colour[$v] > 0) $taken[$colour[$v]] = true; // neighbour's slot
}
$c = 1;
while (isset($taken[$c])) $c++; // smallest free colour
$colour[$u] = $c;
}
return $colour;
}
// subjects: 0 Maths, 1 Science, 2 English, 3 Art, 4 Music
$edges = [[0,1],[0,2],[1,2],[1,3],[2,4],[3,4]];
$adj = array_fill(0, 5, []);
foreach ($edges as [$a, $b]) { $adj[$a][] = $b; $adj[$b][] = $a; }
$slots = colourGraph($adj);
foreach (['Maths', 'Science', 'English', 'Art', 'Music'] as $i => $name) {
echo $name . ' -> slot ' . $slots[$i] . PHP_EOL;
}
echo 'Slots needed: ' . max($slots) . PHP_EOL;JavaScript
// Greedy graph colouring: smallest colour not used by a neighbour
function colourGraph(adj) {
const n = adj.length;
const colour = new Array(n).fill(0); // 0 means "not coloured yet"
for (let u = 0; u < n; u++) {
const taken = new Set();
for (const v of adj[u]) {
if (colour[v] > 0) taken.add(colour[v]); // neighbour's slot
}
let c = 1;
while (taken.has(c)) c++; // smallest free colour
colour[u] = c;
}
return colour;
}
// subjects: 0 Maths, 1 Science, 2 English, 3 Art, 4 Music
const edges = [[0,1],[0,2],[1,2],[1,3],[2,4],[3,4]];
const adj = Array.from({ length: 5 }, () => []);
for (const [a, b] of edges) { adj[a].push(b); adj[b].push(a); }
const slots = colourGraph(adj);
['Maths', 'Science', 'English', 'Art', 'Music'].forEach((name, i) => {
console.log(name + ' -> slot ' + slots[i]);
});
console.log('Slots needed: ' + Math.max(...slots));Java
import java.util.*;
public class Main {
// Greedy graph colouring: smallest colour not used by a neighbour
static int[] colourGraph(List<List<Integer>> adj) {
int n = adj.size();
int[] colour = new int[n]; // 0 means "not coloured yet"
for (int u = 0; u < n; u++) {
Set<Integer> taken = new HashSet<>();
for (int v : adj.get(u)) {
if (colour[v] > 0) taken.add(colour[v]); // neighbour's slot
}
int c = 1;
while (taken.contains(c)) c++; // smallest free colour
colour[u] = c;
}
return colour;
}
public static void main(String[] args) {
// subjects: 0 Maths, 1 Science, 2 English, 3 Art, 4 Music
int[][] edges = {{0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 4}, {3, 4}};
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < 5; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
int[] slots = colourGraph(adj);
String[] names = {"Maths", "Science", "English", "Art", "Music"};
int max = 0;
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + " -> slot " + slots[i]);
max = Math.max(max, slots[i]);
}
System.out.println("Slots needed: " + max);
}
}Go
package main
import "fmt"
// colourGraph is greedy graph colouring: smallest colour not used by a neighbour.
func colourGraph(adj [][]int) []int {
n := len(adj)
colour := make([]int, n) // 0 means "not coloured yet"
for u := 0; u < n; u++ {
taken := map[int]bool{}
for _, v := range adj[u] {
if colour[v] > 0 {
taken[colour[v]] = true // neighbour's slot
}
}
c := 1
for taken[c] { // smallest free colour
c++
}
colour[u] = c
}
return colour
}
func main() {
// subjects: 0 Maths, 1 Science, 2 English, 3 Art, 4 Music
edges := [][2]int{{0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 4}, {3, 4}}
adj := make([][]int, 5)
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
adj[e[1]] = append(adj[e[1]], e[0])
}
slots := colourGraph(adj)
maxSlot := 0
for i, name := range []string{"Maths", "Science", "English", "Art", "Music"} {
fmt.Printf("%s -> slot %d\n", name, slots[i])
maxSlot = max(maxSlot, slots[i])
}
fmt.Println("Slots needed:", maxSlot)
}Time: O(V + E) · Extra space: O(V). Greedy colouring is fast. Finding the <em>fewest possible</em> colours is NP-hard, so greedy gives a good answer, not always the best.
Watch out for
- Believing greedy always finds the minimum number of colours. A bad node order can use more colours than needed.
- Forgetting to look only at neighbours that are already coloured.
- Assuming any map needs a huge number of colours. Planar maps (like real maps) need at most 4 (the Four Colour Theorem), and a graph with no odd cycle needs only 2.
Quick check
- In the timetable story, what does an edge between two subjects mean?
- They are the same subject
- They are taught by the same teacher on purpose
- Some student takes both, so they clash
- Which colour does greedy give a node?
- A random colour
- The smallest colour not used by an already-coloured neighbour
- The same as its first neighbour
- Three subjects that all clash with each other need at least...
- 3 slots
- 1 slot
- 2 slots