progress

~/problems / Graphs / Topological sort (Kahn's)

Minimum Height Trees

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~30 min

A network of n routers, labelled 0 .. n - 1, is wired as a tree: edges holds n - 1 pairs [a, b], each a cable between routers a and b, and every router can reach every other one. If you pick one router as the root, the tree's height is the number of cables on the longest path from the root down to any router.

Write best_roots(n: int, edges: list[list[int]]) -> list[int] that returns every router which, chosen as the root, gives the smallest possible height, in ascending order.

best_roots(7, [[0, 1], [1, 2], [2, 3], [3, 4], [2, 5], [5, 6]])  # [2]      height 2
The seven-router tree hung from router 2: stripping the leaves 0, 4 and 6, then 1, 3 and 5, leaves router 2 as the centre, and as root it gives height 2.
Orange routers are stripped first, yellow second.
best_roots(8, [[i, i + 1] for i in range(7)])                    # [3, 4]   a straight line of 8
best_roots(6, [[4, 0], [4, 1], [4, 2], [4, 3], [4, 5]])          # [4]
best_roots(1, [])                                                # [0]

Constraints: 1 <= n <= 10^5, and edges always forms a tree. The tests include a straight line of 100,000 routers, which overflows Python's recursion limit (about 1,000 frames) if you recurse along it.

⭐ Bonus: measuring the height from every possible root is O(n²); speed tests with 100,000 routers earn a star in O(n).

Show hint

A router at the end of a branch (touching one cable) is never a better root than its neighbour. Strip every such router off at once, and keep going until at most two remain.

Topic: Topological sort (Kahn's). BFS over in-degree-0 nodes; leftover nodes mean a cycle.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc