Topological Sort

Orders the nodes of a directed acyclic graph (DAG) so every edge u → v goes from earlier to later in the order.

Optimal:YesWeighted:NoDirected:YesNegative weights:No
Complexity
Best
O(V + E)
Average
O(V + E)
Worst
O(V + E)
Space
O(V + E)
When to use: When you need to schedule tasks with prerequisites (DAG).Linear time: O(V + E)Does not work if the graph contains a cycle
Pseudocode
compute indegree[v] for all v
enqueue all v with indegree[v] = 0
while queue not empty:
u = dequeue(); output u
for each edge u → v: indegree[v]--; if indegree[v]=0 enqueue v
if output has V nodes, return it; else cycle
Waiting to start…