How it works
Kahn algorithm
Repeatedly remove nodes with no remaining incoming edges, using in-degree counts and a queue.
DFS approach
Run depth-first search and push each node onto a stack after visiting its descendants, then reverse the stack.
Cycle detection
If no valid ordering exists, the graph has a cycle, so topological sort also detects cycles.