← Questions
Topological sort of a directed graph
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's technical phone screen, last asked Jan 2026. It tests graphs and topological sort.
Given a directed graph, return an order of its nodes in which every edge goes from an earlier node to a later one, or report that none exists because the graph has a cycle. Give both Kahn's algorithm and the depth-first version.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
topo_sort(n: int, edges: list[tuple[int, int]]) -> list[int]— nodes are0..n-1; an edge(u, v)meansumust come beforev. Returns any valid order, or[]if there is a cycle.
Example
topo_sort(6, [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]) -> [4, 5, 2, 0, 3, 1] # one valid order
topo_sort(3, [(0, 1), (1, 2), (2, 0)]) -> [] # cycle
topo_sort(3, []) -> [0, 1, 2] # any order works
Constraints
-
1 <= n <= 10^5,0 <= len(edges) <= 2 * 10^5. - Graphs may be disconnected and may contain duplicate edges.
Clarifying questions
- Is any valid order acceptable, or is a specific tie-break wanted (smallest id first)?
- How should a cycle be reported: empty list, an exception, or the cycle itself?
- Can there be self-loops or duplicate edges?
What a strong answer covers
- Kahn's algorithm: compute in-degrees, queue the nodes with in-degree 0, repeatedly output one and decrement its successors; if fewer than
nnodes are output, there is a cycle. - DFS: post-order with three colours (unvisited, on the stack, done); meeting an on-stack node is a cycle; the reversed post-order is a valid order.
- O(n + m) time and space for both, and an iterative DFS to avoid recursion limits.
- Handling disconnected graphs, duplicates and self-loops.
- Tests: a chain, a disconnected graph, a cycle, a self-loop.
Follow-ups
- Return the lexicographically smallest order (a min-heap in Kahn's).
- Return one cycle when the graph is not a DAG.
- Group nodes into levels that can run in parallel, and find the minimum number of rounds.
- Is the topological order unique? Check it in O(n + m).
Where it's asked
- Microsoft · Technical phone screen · Last asked Jan 202660 min · One technical round
What it tests
graphs · topological sort
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
