We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium topological sort problem, graded against 6 test cases (3 of them hidden).
Ordering a directed acyclic graph so every dependency comes first.
Reach for it when you see: Prerequisites, build order, task scheduling, or "can this be completed?"
More Topological Sortproblems →"Every path from here terminates" is awkward to check forwards - it quantifies over all paths. Reversing the graph turns it into something mechanical: a node is safe exactly when all of its successors are safe, and terminal nodes are safe by definition.
So build the reverse graph, and give each node a counter equal to its original outdegree (how many successors it is still waiting on). Terminal nodes start at 0 and seed the queue. Popping a safe node decrements the counter of each node that pointed at it; when a counter hits 0, all of that node's successors have been proven safe, so it is safe too.
This is Kahn's algorithm on the reversed graph, and the same property that gives cycle detection for free does the work here: any node inside a cycle, or with a path into one, never reaches counter 0 and is simply never emitted. Self-loops are handled without a special case - a node pointing at itself can never have its own counter drained.
The DFS three-colour alternative (white/grey/black) is equally valid and worth mentioning in an interview, but the reverse-Kahn version avoids recursion depth concerns at 10^4 nodes.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.