TCS · Question 6
Topological Sort in DAG
Problem
Order vertices in a directed acyclic graph so that every edge u to v appears with u before v.
Approach
Kahn's BFS emits zero-indegree vertices first.
Time O(V+E)Space O(V)
How it works
- 1Count incoming edges per vertex.
- 2Emit zero-indegree vertices, freeing their neighbours.
Sample input / output
Input: V = 6, edges = [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]] Output: [4, 5, 0, 2, 3, 1]
Constraints
Directed acyclic graph.
Solution — read it, then walk it
Time O(V+E)Space O(V)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/15
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits