Kahn's algorithm
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Kahn's algorithm orders tasks by repeatedly starting anything that has no unfinished prerequisites. It naturally shows which tasks can run at the same time, and it exposes loops by running out of ready tasks early.
Practical use cases
- Web app: Background job pipeline. An e-commerce app has jobs: resize images, then generate catalogue PDF, then email the supplier. Each job waits for its inputs. A scheduler counts unfinished prerequisites for each job and queues those at zero, so independent jobs run together on several workers.
- Web app: Installing plugins in a CMS. A site installs 12 plugins, some needing others. The installer counts dependencies for each, installs those with none first, and reduces the count of the rest as it goes, finishing in a valid order.
- Web app: Semester timetable builder. A college portal has subjects with prerequisites. Each round lists every subject whose prerequisites are done, and that round becomes one semester. Students see a plan like "Semester 1: A, B; Semester 2: C".
- System: Task schedulers and loop detection. Build tools and workflow engines use this ready-count technique, and if tasks remain but none is ready, they know a circular dependency is stuck. The simple rule of "start whatever has nothing left to wait for" makes it easy to explain to users why a job has not started yet.
The story: The Wedding Kitchen Queue
Grandpa Bhaskar was in charge of the kitchen for a family wedding, and the cooks were all standing around confused. "I cannot fry the pakoras before the batter is made," said one. "I cannot make the batter before the flour is sifted," said another. Everyone was waiting for someone else.
Mira, carrying a tray of chai, had a thought. "Let me ask each cook one question: how many jobs are you still waiting on?" The sifter said zero. The man who washes vegetables said zero. The batter maker said one, the frier said two.
"The ones with zero can start right now!" she announced. She wrote them on a board, the ready queue. When the sifter finished, Mira crossed one waiting job off everybody who was waiting on the sifter. The batter maker's count dropped to zero, so his name joined the board. One by one the whole kitchen got cooking, in a perfectly safe order.
This is Kahn's algorithm: repeatedly pick a task with nobody blocking it, finish it, and release the tasks it was blocking. And the best bonus: if the board becomes empty while some cooks still wait on each other, you have found a cycle.
How to spot this problem, and where you need it
You have tasks with dependencies and want to run them in a valid order, ideally in groups of tasks that can safely run at the same time, and be told if something is stuck.
Signs you need it
- You can describe each task by "how many things must finish before me".
- You want rounds or batches, such as "what can run now?", not just one long list.
- The scheduler hangs or silently skips tasks, which hints at a dependency loop.
Where to use it in a project
- A queue worker or workflow tool that decides which job to start next as others finish.
- Installers and planners that group steps into stages, such as semesters, sprints or deployment steps.
The solution
Count for each node how many arrows point into it (its in-degree). Put all nodes with count 0 in a queue. Take one out, add it to the result, and for each node it points to reduce that count by one; whenever a count reaches 0, add that node to the queue. Continue until the queue is empty. If the result has fewer nodes than the total, some nodes are stuck in a loop.
Payoff: Before: jobs run one by one in a fixed order, taking 10 minutes. After: independent jobs run in parallel waves and finish in 4.
Explain it like I am 8
Each kid in the queue holds a card with "how many friends must go before me". Kids with 0 go first. Each time a kid goes, everybody who was waiting on that kid lowers their number by 1. Anyone who hits 0 joins the line.
How it works, step by step
- For every node count its in-degree: how many arrows point into it.
- Put every node with in-degree 0 into a queue.
- Take a node from the front of the queue and add it to the answer.
- For each node it points to, subtract 1 from that node's in-degree. If it reaches 0, push it into the queue.
- Repeat until the queue is empty. If the answer has fewer nodes than the graph, there is a cycle.
The code in four languages
PHP
<?php
// Kahn's algorithm: returns the order, or null if there is a cycle
function kahn(int $n, array $edges): ?array {
$adj = array_fill(0, $n, []);
$waiting = array_fill(0, $n, 0); // in-degree: jobs each task waits on
foreach ($edges as [$from, $to]) {
$adj[$from][] = $to;
$waiting[$to]++;
}
$queue = [];
for ($i = 0; $i < $n; $i++) {
if ($waiting[$i] === 0) $queue[] = $i; // nobody blocks these
}
$order = [];
for ($head = 0; $head < count($queue); $head++) {
$u = $queue[$head];
$order[] = $u;
foreach ($adj[$u] as $v) {
$waiting[$v]--; // u is finished, v waits for one less
if ($waiting[$v] === 0) $queue[] = $v;
}
}
return count($order) === $n ? $order : null; // fewer than n means a cycle
}
$names = ['A', 'B', 'C', 'D', 'E', 'F'];
$edges = [[0,2],[1,2],[2,3],[1,4],[3,5],[4,5]];
$order = kahn(6, $edges);
echo implode(' ', array_map(fn($i) => $names[$i], $order)) . PHP_EOL;
// two tasks waiting on each other: a cycle
var_dump(kahn(2, [[0,1],[1,0]]));JavaScript
// Kahn's algorithm: returns the order, or null if there is a cycle
function kahn(n, edges) {
const adj = Array.from({ length: n }, () => []);
const waiting = new Array(n).fill(0); // in-degree: jobs each task waits on
for (const [from, to] of edges) {
adj[from].push(to);
waiting[to]++;
}
const queue = [];
for (let i = 0; i < n; i++) {
if (waiting[i] === 0) queue.push(i); // nobody blocks these
}
const order = [];
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
order.push(u);
for (const v of adj[u]) {
waiting[v]--; // u is finished, v waits for one less
if (waiting[v] === 0) queue.push(v);
}
}
return order.length === n ? order : null; // fewer than n means a cycle
}
const names = ['A', 'B', 'C', 'D', 'E', 'F'];
const edges = [[0,2],[1,2],[2,3],[1,4],[3,5],[4,5]];
const order = kahn(6, edges);
console.log(order.map(i => names[i]).join(' '));
// two tasks waiting on each other: a cycle
console.log(kahn(2, [[0,1],[1,0]]));Java
import java.util.*;
public class Main {
// Kahn's algorithm: returns the order, or null if there is a cycle
static List<Integer> kahn(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] waiting = new int[n]; // in-degree: jobs each task waits on
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
waiting[e[1]]++;
}
List<Integer> queue = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (waiting[i] == 0) queue.add(i); // nobody blocks these
}
List<Integer> order = new ArrayList<>();
for (int head = 0; head < queue.size(); head++) {
int u = queue.get(head);
order.add(u);
for (int v : adj.get(u)) {
waiting[v]--; // u is finished, v waits for one less
if (waiting[v] == 0) queue.add(v);
}
}
return order.size() == n ? order : null; // fewer than n means a cycle
}
public static void main(String[] args) {
String[] names = {"A", "B", "C", "D", "E", "F"};
int[][] edges = {{0, 2}, {1, 2}, {2, 3}, {1, 4}, {3, 5}, {4, 5}};
List<String> words = new ArrayList<>();
for (int i : kahn(6, edges)) words.add(names[i]);
System.out.println(String.join(" ", words));
// two tasks waiting on each other: a cycle
System.out.println(kahn(2, new int[][]{{0, 1}, {1, 0}})); // null
}
}Go
package main
import (
"fmt"
"strings"
)
// kahn returns the order, or ok=false if there is a cycle.
func kahn(n int, edges [][2]int) (order []int, ok bool) {
adj := make([][]int, n)
waiting := make([]int, n) // in-degree: jobs each task waits on
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
waiting[e[1]]++
}
var queue []int
for i := 0; i < n; i++ {
if waiting[i] == 0 {
queue = append(queue, i) // nobody blocks these
}
}
for head := 0; head < len(queue); head++ {
u := queue[head]
order = append(order, u)
for _, v := range adj[u] {
waiting[v]-- // u is finished, v waits for one less
if waiting[v] == 0 {
queue = append(queue, v)
}
}
}
return order, len(order) == n // fewer than n means a cycle
}
func main() {
names := []string{"A", "B", "C", "D", "E", "F"}
edges := [][2]int{{0, 2}, {1, 2}, {2, 3}, {1, 4}, {3, 5}, {4, 5}}
order, _ := kahn(6, edges)
var words []string
for _, i := range order {
words = append(words, names[i])
}
fmt.Println(strings.Join(words, " "))
// two tasks waiting on each other: a cycle
if _, ok := kahn(2, [][2]int{{0, 1}, {1, 0}}); !ok {
fmt.Println("null") // no order exists
}
}Time: O(V + E) · Extra space: O(V + E). Every node enters the queue once and every arrow is crossed off once.
Watch out for
- Forgetting to compare the answer length with the node count at the end. That check is exactly how a cycle shows up.
- Calling queue.shift() inside a hot loop on a huge array. Use a moving head pointer (as in the code) so each pop is O(1).
- Counting the in-degree wrongly when the input has duplicate arrows. Count every arrow consistently when building and when subtracting.
Quick check
- Which nodes start in the queue?
- Nodes with no outgoing arrows
- Nodes with in-degree 0
- The biggest node
- After finishing node u, what do we do?
- Reduce the in-degree of every node u points to
- Move u to the back of the queue
- Delete the whole graph
- The queue becomes empty but only 4 of 6 nodes were output. What does that mean?
- The graph is perfectly fine
- We need a bigger queue
- The graph has a cycle