Problem
Section titled “Problem”Given a Directed Acyclic Graph (DAG) with V vertices numbered from 0 to V - 1, represented by an adjacency list adj[][], return a topological ordering of its vertices.
A topological ordering is a linear ordering of vertices such that for every directed edge u -> v, vertex u appears before vertex v in the ordering.
Note: Multiple valid topological orderings may exist. Any valid ordering is accepted. The output is true if the returned ordering is valid; otherwise, it is false.
Complete the function topoSort() which takes the adjacency list adj and returns a list of all V vertices in topological order.
Example 1:

Input: adj[][] = [[], [0], [0], [0]]Output: trueExplanation: The output true denotes that the order is valid. Few valid topological ordersfor the given graph are:[3, 2, 1, 0][1, 2, 3, 0][2, 3, 1, 0]Example 2:

Input: adj[][] = [[], [3], [3], [], [1, 0], [0, 2]]Output: trueExplanation: The output true denotes that the order is valid. Few valid topological ordersfor the graph are:[4, 5, 0, 1, 2, 3][5, 2, 4, 0, 1, 3]Constraints:
-
adj.size() -
adj[i][j]adj.size()
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”A vertex with no incoming edges (in-degree 0) has no vertex that must come before it, so it can safely be placed first. Once it is placed, its outgoing edges no longer constrain anything, so we can delete them; this lowers the in-degree of its neighbours, and any neighbour that reaches in-degree 0 becomes safe to place next.
Repeating this is Kahn’s algorithm. The invariant is: a vertex is appended to the answer only after every vertex with an edge into it has already been appended (that is exactly what in-degree 0 means after the deletions). So every edge u -> v has u before v. Because the graph is acyclic, there is always at least one vertex of in-degree 0 left until all vertices are placed.
Unlike the DFS-with-a-stack approach, this is iterative, so a long chain of vertices cannot overflow the call stack.
Algorithm
Section titled “Algorithm”- Count
indegree[v]for every vertex by scanning every edgeu -> vinadj. - Append every vertex with
indegree[u] == 0toorder.orderdoubles as the BFS queue:order[head..]are vertices that are placed but whose edges are not yet removed. - For
head = 0, 1, ...whilehead < order.size(): takeu = order[head]and, for each neighbourvinadj[u], decrementindegree[v]; if it becomes0, appendvtoorder. - Return
order; it contains allVvertices because the input is a DAG.
Walkthrough
Section titled “Walkthrough”Example 2. The initial in-degrees are 0:2, 1:1, 2:1, 3:2, 4:0, 5:0. Green vertices start with in-degree 0:
| Step | Remove edges of | In-degrees that drop to 0 | order |
|---|---|---|---|
| start | — | 4, 5 | [4, 5] |
| 1 | 4 | 1 (0 drops to 1) | [4, 5, 1] |
| 2 | 5 | 0, 2 | [4, 5, 1, 0, 2] |
| 3 | 1 | — (3 drops to 1) | [4, 5, 1, 0, 2] |
| 4 | 0 | — | [4, 5, 1, 0, 2] |
| 5 | 2 | 3 | [4, 5, 1, 0, 2, 3] |
| 6 | 3 | — | [4, 5, 1, 0, 2, 3] |
Complexity
Section titled “Complexity”- Time: — each vertex is appended and processed once, and each edge is looked at twice (once when counting in-degrees, once when it is removed).
- Space: — the
indegreearray andorder; no recursion.
Edge cases
Section titled “Edge cases”- Disconnected graph / isolated vertices (vertex
3in Example 2 has no outgoing edges, and a vertex may have no edges at all): every vertex with in-degree0is seeded in step 2, so each component is reached. - Parallel edges (
u -> vlisted twice):indegree[v]counts both and both are removed, sovis still released exactly once.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: vector<int> topoSort(vector<vector<int>>& adj) { int V = adj.size(); vector<int> indegree(V, 0); for (int u = 0; u < V; u++) for (int v : adj[u]) indegree[v]++;
vector<int> order; order.reserve(V); for (int u = 0; u < V; u++) if (indegree[u] == 0) order.push_back(u);
// order doubles as the BFS queue: order[head..] still have edges to remove. for (size_t head = 0; head < order.size(); head++) { int u = order[head]; for (int v : adj[u]) if (--indegree[v] == 0) order.push_back(v); } return order; }};class Solution { ArrayList<Integer> topoSort(ArrayList<ArrayList<Integer>> adj) { int V = adj.size(); int[] indegree = new int[V]; for (ArrayList<Integer> edges : adj) for (int v : edges) indegree[v]++;
ArrayList<Integer> order = new ArrayList<>(V); for (int u = 0; u < V; u++) if (indegree[u] == 0) order.add(u);
// order doubles as the BFS queue: order[head..] still have edges to remove. for (int head = 0; head < order.size(); head++) { for (int v : adj.get(order.get(head))) if (--indegree[v] == 0) order.add(v); } return order; }}class Solution: def topoSort(self, adj: list[list[int]]) -> list[int]: indegree = [0] * len(adj) for edges in adj: for v in edges: indegree[v] += 1
order = [u for u in range(len(adj)) if indegree[u] == 0] # order doubles as the BFS queue: the loop also visits vertices appended during it. for u in order: for v in adj[u]: indegree[v] -= 1 if indegree[v] == 0: order.append(v) return orderGive it a try first
Attempt the problem on GeeksforGeeks — the code will still be here.
