Kahn’s topological sort

Put tasks in an order that respects what each one needs. For example, bake a cake before decorating it. An arrow leads from the earlier task to the one that needs it.

Count incoming arrows. Queue every task with no unmet prerequisites. Completing one releases its outgoing arrows. Unfinished tasks and an empty queue reveal a cycle.

With adjacency lists, traversal takes O(V + E) time for V vertices and E edges.