Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are the centres.

Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are the centres.
def mht_roots(n, edges):
    if n <= 2: return list(range(n))
    adj = [set() for _ in range(n)]
    for a, b in edges: adj[a].add(b); adj[b].add(a)
    leaves = [i for i in range(n) if len(adj[i]) == 1]; left = n
    while left > 2:
        left -= len(leaves); nxt = []
        for x in leaves:
            y = adj[x].pop(); adj[y].discard(x)
            if len(adj[y]) == 1: nxt.append(y)
        leaves = nxt
    return sorted(leaves)
print(mht_roots(7, [(0, 1), (1, 2), (2, 3), (3, 4), (2, 5), (5, 6)]), mht_roots(6, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]))
What is printed?
  1. A. [1, 2] [2, 3]
  2. B. [2] [3]
  3. C. [2, 3] [2, 3]
  4. D. [2] [2, 3]

Correct answer: D. [2] [2, 3]

The optimal roots are the centre(s) of a longest path, found by peeling leaves layer by layer (topological trimming). Tree 1: longest paths have 4 edges (e.g. 0-1-2-3-4, 0-1-2-5-6), so node 2 alone gives height 2. The path of 6 nodes has two centres, 2 and 3. Running BFS from every node also works but costs O(n²); trimming is O(n).

More Coding Interview Problems questions

Exams that ask this topic