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)- A. [2] 5
- B. [3] 4
- C. [3, 5] 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost…
- Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed? python…
- Match each recurrence to its tight bound: (P) T(n) = 2T(n/2) + n log n (Q) T(n) = 2T(n/2) + n / log n (R) T(n) = T(n/2) + log n (S) T(n) =…
- A road network has n ≤ 2·10⁵ junctions and m ≤ 2·10⁵ roads; each road is either free (0) or tolled (1). You need the minimum number of…
- Which loop nests perform Θ(n log n) executions of work()? c / A / for (i = 1; i <= n; i++) for (j = i; j <= n; j += i) work(); / B / for…
- A full binary tree (every node has 0 or 2 children) has 10 internal nodes. How many leaves does it have?