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 →The brute force runs a traversal from every node - O(V x (V + E)). The better framing: ancestry is transitive, so a node's ancestors are the union of its parents' ancestors plus the parents themselves.
That recurrence needs each parent finished before the child, which is precisely what a topological order guarantees. So run Kahn's algorithm and, when relaxing edge `u -> v`, merge `ancestors[u]` into `ancestors[v]` and add `u`. When `v` finally pops, its set is complete, because every incoming edge was relaxed before its indegree reached zero.
Sets rather than lists matter here: with multiple paths between two nodes (the 5-node example is dense) a list would accumulate duplicates. Sort each set at the end to satisfy the ordering requirement.
This is a good demonstration that topological sort is not only about ordering - it is the schedule that lets any "depends on everything upstream" quantity be computed in one pass. Longest path in a DAG and DAG shortest paths use the identical skeleton.
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.