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 →Rooting at each node and measuring the height is O(n^2) and will not pass. The structural insight: the height-minimizing roots are the centres of the tree, the midpoint(s) of its longest path (its diameter). A path with an odd number of nodes has one midpoint, an even number has two - which is exactly why the answer is always one or two nodes.
Rather than finding the diameter explicitly, peel inwards. Every node of degree 1 is a leaf and is a worst possible root, so remove the whole leaf layer at once, then recompute which nodes have become leaves and repeat. Each round strips one layer from every branch simultaneously, so the last survivors are equidistant from the extremities - the centre.
Structurally this is Kahn's algorithm on an undirected graph, with degree in place of indegree, which is why it lives in the topological-sort family despite not being a DAG problem.
Stop as soon as 2 or fewer nodes remain. The `n == 1` case needs handling first: a lone node has degree 0, never matches the degree-1 leaf test, and would otherwise be peeled to nothing.
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.