Topological Sort (Kahn's BFS)
Order the vertices of a DAG so every edge points forward. Kahn's algorithm uses in-degrees.
Open on GeeksforGeeks ↗Intuition
A vertex is ready to be output only when every prerequisite is already out — and 'no remaining prerequisites' is exactly in-degree == 0. Start with all such vertices, and each time you output one, remove its edges, which may free others. If the process stalls before covering every vertex, the leftovers form a cycle.
Approach
Count incoming edges
Scan every adjacency list once, incrementing indeg[v] for each edge u → v. Vertices with in-degree 0 depend on nothing and can go first.
Peel in waves
Queue all zero-degree vertices. Pop one, append it to the order, and decrement the in-degree of each target — any that hits 0 is newly unblocked and joins the queue.
Cycle detection for free
In a DAG every vertex eventually reaches in-degree 0. If the output is shorter than V, the remaining vertices each still wait on another — that is a cycle, so no ordering exists.
Solution & live demo
Edge cases
Fewer than V vertices are output; return empty / report failure.
Any is acceptable; queue order decides which one appears.
Every vertex starts at in-degree 0 — any permutation is valid.