intermediate · topological sort · Kahn's algorithm · graphs · queue
An order that respects every dependency
Problem
A build has n steps numbered 0 to n − 1 and a list of rules "a before b". Return an order of all steps that obeys every rule, or report that none exists because the rules contain a loop.
So that every language gives the same answer: start with the steps that wait on nothing, in increasing number; always take the step that has been ready longest (a queue); and release the steps that wait on it in the order their rules were given. In the lab, enter the rules as one list: a b a b …
Constraints
- 1 ≤ n ≤ 12
- 0 ≤ rules ≤ 16
Examples
n = 4, rules = [[0, 2], [1, 2], [2, 3]] → [0, 1, 2, 3]
n = 2, rules = [[0, 1], [1, 0]] → cycle
Show the solution
Kahn's algorithm with a FIFO queue
Steps that wait on nothing can always go next. Doing one of them can only free further steps, never block any.
Why it is correct
A step is appended only when every rule "x before it" has had x appended, so the order respects all rules. If the rules have no loop, some unfinished step always has count 0 (otherwise following "waits on" backwards from any unfinished step would cycle), so all n steps are appended. If there is a loop, no step on it ever reaches count 0, so fewer than n steps come out and the answer is "cycle".
Complexity
Time O(n + m), extra space O(n + m). Building the adjacency lists and counts is O(n + m); each step is dequeued once and each rule decreases one count once.
For contrast: A loop exists exactly when some step can reach itself (transitive closure); otherwise check that the returned order is a permutation obeying every rule. That costs O(n³) time and O(n²) space.
Edge cases
- No rules: 0, 1, …, n − 1.
- A rule "a before a" is a loop.
- Repeated rules count twice and are released twice.
Common mistakes
- Returning the partial order when a loop exists.
- Counting a step's outgoing rules instead of its incoming ones.
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class TaskOrder
{
/// <summary>Kahn's algorithm with a FIFO queue (seeded in increasing order, releases in rule order). Empty when the rules loop. O(n + m).</summary>
public static List<int> Order(int n, IEnumerable<(int Before, int After)> rules)
{
var unlocks = Enumerable.Range(0, n).Select(_ => new List<int>()).ToArray();
var waitingOn = new int[n]; // in-degree: rules not yet satisfied
foreach (var (before, after) in rules)
{
unlocks[before].Add(after);
waitingOn[after]++;
}
var ready = new Queue<int>(Enumerable.Range(0, n).Where(t => waitingOn[t] == 0));
var order = new List<int>();
while (ready.Count > 0)
{
int task = ready.Dequeue();
order.Add(task);
foreach (int after in unlocks[task])
{
if (--waitingOn[after] == 0) ready.Enqueue(after);
}
}
return order.Count == n ? order : []; // leftovers wait on each other: a loop
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/TaskOrder.cs
from collections import deque
from collections.abc import Iterable
def order(n: int, rules: Iterable[tuple[int, int]]) -> list[int]:
"""Kahn's algorithm, FIFO queue seeded in increasing order, releases in rule order. Empty when the rules loop. O(n + m)."""
unlocks: list[list[int]] = [[] for _ in range(n)]
waiting_on = [0] * n # in-degree: rules not yet satisfied
for before, after in rules:
unlocks[before].append(after)
waiting_on[after] += 1
ready = deque(t for t in range(n) if waiting_on[t] == 0)
result: list[int] = []
while ready:
task = ready.popleft()
result.append(task)
for after in unlocks[task]:
waiting_on[after] -= 1
if waiting_on[after] == 0:
ready.append(after)
return result if len(result) == n else [] # leftovers wait on each other: a loop
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/task_order.py
package dev.bekadan.dsa.problems;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public final class TaskOrder {
private TaskOrder() {
}
/** Kahn's algorithm, FIFO queue seeded in increasing order, releases in rule order. Empty when the rules loop. O(n + m). */
public static List<Integer> order(int n, int[][] rules) {
List<List<Integer>> unlocks = new ArrayList<>();
for (int i = 0; i < n; i++) {
unlocks.add(new ArrayList<>());
}
int[] waitingOn = new int[n]; // in-degree: rules not yet satisfied
for (int[] rule : rules) {
unlocks.get(rule[0]).add(rule[1]);
waitingOn[rule[1]]++;
}
Deque<Integer> ready = new ArrayDeque<>();
for (int t = 0; t < n; t++) {
if (waitingOn[t] == 0) {
ready.add(t);
}
}
List<Integer> order = new ArrayList<>();
while (!ready.isEmpty()) {
int task = ready.poll();
order.add(task);
for (int after : unlocks.get(task)) {
if (--waitingOn[after] == 0) {
ready.add(after);
}
}
}
return order.size() == n ? order : List.of(); // leftovers wait on each other: a loop
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/TaskOrder.java
#pragma once
#include <cstddef>
#include <queue>
#include <utility>
#include <vector>
namespace bekadan::dsa::problems {
// Kahn's algorithm, FIFO queue seeded in increasing order, releases in rule order. Empty when the rules loop. O(n + m).
inline std::vector<int> task_order(std::size_t n, const std::vector<std::pair<int, int>>& rules) {
std::vector<std::vector<std::size_t>> unlocks(n);
std::vector<int> waiting_on(n, 0); // in-degree: rules not yet satisfied
for (const auto& [before, after] : rules) {
unlocks[static_cast<std::size_t>(before)].push_back(static_cast<std::size_t>(after));
++waiting_on[static_cast<std::size_t>(after)];
}
std::queue<std::size_t> ready;
for (std::size_t t = 0; t < n; ++t) {
if (waiting_on[t] == 0) ready.push(t);
}
std::vector<int> order;
while (!ready.empty()) {
const std::size_t task = ready.front();
ready.pop();
order.push_back(static_cast<int>(task));
for (const std::size_t after : unlocks[task]) {
if (--waiting_on[after] == 0) ready.push(after);
}
}
if (order.size() != n) order.clear(); // leftovers wait on each other: a loop
return order;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/task_order.hpp