Data Structures & AlgorithmsVery hardProduct company OA

Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s), that largest component)?

Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s), that largest component)?
n = 10
edges = [(1, 2), (2, 3), (3, 4), (3, 5), (5, 6), (5, 7), (7, 8), (2, 9), (9, 10)]
adj = {i: [] for i in range(1, n + 1)}
for a, b in edges: adj[a].append(b); adj[b].append(a)
size = {}
def dfs(u, p):
    size[u] = 1
    for v in adj[u]:
        if v != p: dfs(v, u); size[u] += size[v]
dfs(1, 0)
def worst(u):
    parts = [n - size[u]] + [size[v] for v in adj[u] if size[v] < size[u]]
    return max(parts)
best = min(worst(u) for u in adj)
print([u for u in adj if worst(u) == best], best)
  1. A. [2] 5
  2. B. [3] 4
  3. C. [3, 5] 4
  4. D. [5] 5

Correct answer: B. [3] 4

With subtree sizes from one DFS, removing u leaves its child subtrees and the 'upward' part n − size[u]. For vertex 3 the parts are {1, 2, 9, 10} (4), {4} (1) and {5, 6, 7, 8} (4) → worst 4 ≤ n/2 = 5. Vertex 2 leaves {3..8} of size 6, vertex 5 leaves {1, 2, 3, 4, 9, 10} of size 6, so 3 is the unique centroid. A tree has at most two centroids, and always one whose largest part is ≤ n/2. O(n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic