AlgoTales · Roadmap

Topological sorting

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A topological sort puts tasks in a line so that every task comes after everything it depends on. It only exists when there are no circular dependencies, which makes it also a handy check that a plan is possible.

Practical use cases

  • Web app: Running database migrations in order. A Laravel-style project has dozens of migrations where one table needs another to exist first. The runner must put them in a safe order so foreign keys never point at missing tables. A sorted list prevents the "table not found" failure on a fresh server.
  • Web app: Online course unlock order. A learning site has courses with prerequisites. The "recommended path" page lists them in an order where each course appears after its prerequisites, so a new student can just go top to bottom. The site can also gently grey out courses whose earlier steps are not done.
  • Web app: Spreadsheet or report calculation order. A dashboard has computed fields, like Profit = Revenue minus Cost, and Margin = Profit divided by Revenue. Calculating fields in dependency order means each value is ready before it is used, with no repeats. Without that order the dashboard would either show blanks or recalculate the same field many times, and the page would feel sluggish.
  • System: Build systems and package installers. Tools like make and package managers compile or install the pieces that others need first, then the rest. In every case you simply place things so that anything required comes first, and a failure to do so tells you the rules loop.

The story: Mira's Rush-Hour Morning

Every school morning Mira's house turned into a traffic jam. Mama's rules were famous: "You cannot put shoes on before you are dressed. You cannot get dressed before your bath. And nobody eats tiffin before waking up!" Mira kept breaking the rules in a different order every day, and always ran late.

Kabir took a notebook and drew an arrow for every rule. Wake up → Bath. Bath → Dress. Dress → Shoes. Wake up → Tiffin. "Now," he said, "I just need to write the tasks in a single line so that every arrow points to the right. Then you do them left to right and no rule can ever break."

Mira noticed something funny. The line was not unique! Tiffin could come before or after the bath, and both lines worked. But if anyone wrote a rule like "Bath needs Dress, Dress needs Bath", no line could ever satisfy it. A rule loop like that is impossible, and Kabir learned to spot it.

Kabir's single line is called a topological order, and finding it is topological sorting. It only works on a directed graph with no cycles (a DAG).

How to spot this problem, and where you need it

Some things must be done, built or loaded before others, and you need one valid order that respects every "A before B" rule.

Signs you need it

  • The problem has "must come before", "depends on", "prerequisite" or "requires", and the question is "in what order?".
  • Things break only when run in a certain order, for example a script that fails with a missing-value error until another one runs first.
  • Items and rules form arrows that must not loop, and you need to know if they do.

Where to use it in a project

  • A migration, seeder, plugin or module loader that must start items in dependency order.
  • A course, project or CI pipeline planner that lists steps so nothing starts before its inputs are ready.

The solution

Treat each item as a node and each "A before B" rule as an arrow from A to B. Then produce a list using one of two methods: repeatedly take any item with no unmet prerequisites (Kahn), or run DFS and list items in reverse order of finishing. If you cannot place all items, the rules contain a loop and no valid order exists, which you report to the user.

Payoff: Before: migrations failing on a clean server about half the time. After: one computed order runs all 60 migrations successfully every time.

Explain it like I am 8

You are stacking a tower of blocks, and some blocks have to be placed before others. A topological sort is the list of blocks in a safe building order: if block A must go below block B, A is always earlier in your list.

How it works, step by step

  1. Draw each task as a node and each rule "X before Y" as an arrow X → Y.
  2. Look for any cycle (a loop of arrows that returns to where it started). If there is one, no valid order exists.
  3. Otherwise, line the nodes up so that every arrow points from earlier to later.
  4. There can be many valid lines. Any one of them is a correct answer.
  5. To check a given line, find the position of each task and make sure for every arrow pos[X] < pos[Y]. To build a line, use Kahn's algorithm or the DFS method (next lessons).

The code in four languages

PHP

<?php
// Is this line-up a valid topological order?
// $rules is a list of [first, then] pairs: "first must come before then"
function isValidOrder(array $order, array $rules): bool {
    $place = array_flip($order);                  // task => position in the line
    foreach ($rules as [$first, $then]) {
        if (!isset($place[$first]) || !isset($place[$then])) return false;
        if ($place[$first] > $place[$then]) return false;   // arrow points backwards!
    }
    return true;
}

$rules = [['wake', 'bath'], ['wake', 'tiffin'], ['bath', 'dress'],
          ['dress', 'shoes'], ['shoes', 'school'], ['tiffin', 'school']];

$a = ['wake', 'bath', 'dress', 'shoes', 'tiffin', 'school'];
$b = ['wake', 'tiffin', 'bath', 'dress', 'shoes', 'school'];
$c = ['bath', 'wake', 'tiffin', 'dress', 'shoes', 'school'];
echo 'A: ' . (isValidOrder($a, $rules) ? 'valid' : 'invalid') . PHP_EOL;
echo 'B: ' . (isValidOrder($b, $rules) ? 'valid' : 'invalid') . PHP_EOL;
echo 'C: ' . (isValidOrder($c, $rules) ? 'valid' : 'invalid') . PHP_EOL;

JavaScript

// Is this line-up a valid topological order?
// rules is a list of [first, then] pairs: "first must come before then"
function isValidOrder(order, rules) {
  const place = {};                               // task => position in the line
  order.forEach((task, i) => { place[task] = i; });
  for (const [first, then] of rules) {
    if (!(first in place) || !(then in place)) return false;
    if (place[first] > place[then]) return false; // arrow points backwards!
  }
  return true;
}

const rules = [['wake', 'bath'], ['wake', 'tiffin'], ['bath', 'dress'],
               ['dress', 'shoes'], ['shoes', 'school'], ['tiffin', 'school']];

const a = ['wake', 'bath', 'dress', 'shoes', 'tiffin', 'school'];
const b = ['wake', 'tiffin', 'bath', 'dress', 'shoes', 'school'];
const c = ['bath', 'wake', 'tiffin', 'dress', 'shoes', 'school'];
console.log('A: ' + (isValidOrder(a, rules) ? 'valid' : 'invalid'));
console.log('B: ' + (isValidOrder(b, rules) ? 'valid' : 'invalid'));
console.log('C: ' + (isValidOrder(c, rules) ? 'valid' : 'invalid'));

Java

import java.util.*;

public class Main {
    // Is this line-up a valid topological order?
    // rules is a list of {first, then} pairs: "first must come before then"
    static boolean isValidOrder(List<String> order, String[][] rules) {
        Map<String, Integer> place = new HashMap<>();      // task -> position in the line
        for (int i = 0; i < order.size(); i++) place.put(order.get(i), i);
        for (String[] rule : rules) {
            String first = rule[0], then = rule[1];
            if (!place.containsKey(first) || !place.containsKey(then)) return false;
            if (place.get(first) > place.get(then)) return false;   // arrow points backwards!
        }
        return true;
    }

    public static void main(String[] args) {
        String[][] rules = {{"wake", "bath"}, {"wake", "tiffin"}, {"bath", "dress"},
                            {"dress", "shoes"}, {"shoes", "school"}, {"tiffin", "school"}};

        var a = List.of("wake", "bath", "dress", "shoes", "tiffin", "school");
        var b = List.of("wake", "tiffin", "bath", "dress", "shoes", "school");
        var c = List.of("bath", "wake", "tiffin", "dress", "shoes", "school");
        System.out.println("A: " + (isValidOrder(a, rules) ? "valid" : "invalid"));
        System.out.println("B: " + (isValidOrder(b, rules) ? "valid" : "invalid"));
        System.out.println("C: " + (isValidOrder(c, rules) ? "valid" : "invalid"));
    }
}

Go

package main

import "fmt"

// isValidOrder reports whether this line-up is a valid topological order.
// rules is a list of {first, then} pairs: "first must come before then".
func isValidOrder(order []string, rules [][2]string) bool {
	place := map[string]int{} // task -> position in the line
	for i, task := range order {
		place[task] = i
	}
	for _, rule := range rules {
		first, okFirst := place[rule[0]]
		then, okThen := place[rule[1]]
		if !okFirst || !okThen {
			return false
		}
		if first > then {
			return false // arrow points backwards!
		}
	}
	return true
}

func verdict(valid bool) string {
	if valid {
		return "valid"
	}
	return "invalid"
}

func main() {
	rules := [][2]string{{"wake", "bath"}, {"wake", "tiffin"}, {"bath", "dress"},
		{"dress", "shoes"}, {"shoes", "school"}, {"tiffin", "school"}}

	a := []string{"wake", "bath", "dress", "shoes", "tiffin", "school"}
	b := []string{"wake", "tiffin", "bath", "dress", "shoes", "school"}
	c := []string{"bath", "wake", "tiffin", "dress", "shoes", "school"}
	fmt.Println("A: " + verdict(isValidOrder(a, rules)))
	fmt.Println("B: " + verdict(isValidOrder(b, rules)))
	fmt.Println("C: " + verdict(isValidOrder(c, rules)))
}

Time: O(V + E) · Extra space: O(V). Checking an order looks at every task and every rule once; building one with Kahn or DFS costs the same.

Watch out for

  • Trying to topologically sort a graph that has a cycle. There is simply no answer; detect it and report an error.
  • Assuming the answer is unique. Two correct programs can print different (both valid) orders.
  • Using it on an undirected graph. Without arrow directions there is no "before".

Quick check

  1. What does an arrow A → B mean in a topological sort?
    • A must come before B
    • B must come before A
    • A and B are friends
  2. When is a topological order impossible?
    • When two nodes have no arrow between them
    • When there are too many nodes
    • When the graph has a cycle
  3. Can a graph have several valid topological orders?
    • Never, it is unique
    • Yes, when some tasks do not depend on each other
    • Only if it has a cycle