Graph Theory37 sections · 1633 units
Open in Course

Pattern - Lexicographical Order

Controlling the Choice

Sometimes you need the lexicographically smallest topological order. Standard Kahn's algorithm uses a regular queue and picks nodes arbitrarily when multiple have in-degree 00.

To get the smallest order, replace the queue with a min-heap (priority queue). When multiple nodes have in-degree 00, the heap always gives you the smallest one first. This guarantees the lexicographically smallest valid topological ordering.

Example: Topological Sorting on SPOJ requires you to output the smallest valid permutation.