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?- A. [1, 2] [2, 3]
- B. [2] [3]
- C. [2, 3] [2, 3]
- 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
- Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the…
- Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones…
- Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row. python def pascalrow(k): row =…
- Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1. python def no11(n)…
- Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three…
- Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed…