Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Find all roots that give a tree of minimum height, by repeatedly peeling off leaves.
Problem: Find all roots that give a tree of minimum height, by repeatedly peeling off leaves.
def mht(n, edges):
adj = [set() for _ in range(n)]
for u, v in edges: adj[u].add(v); adj[v].add(u)
leaves = [i for i in range(n) if len(adj[i]) <= 1]; rem = n
while rem > 2:
rem -= len(leaves); nl = []
for x in leaves:
y = adj[x].pop(); adj[y].discard(x)
if len(adj[y]) == 1: nl.append(y)
leaves = nl
return sorted(leaves)
print(mht(7, [(0,1),(1,2),(2,3),(3,4),(2,5),(5,6)]))What is printed?- A. [1, 2]
- B. [2]
- C. [2, 3]
- D. [2, 5]
Correct answer: B. [2]
Peeling leaves {0, 4, 6}, then {1, 3, 5}, leaves only node 2. Both longest paths (0–1–2–3–4 and 0–1–2–5–6) have 4 edges, an even length, so there is exactly one centre.
More Coding Interview Problems questions
- Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length)…
- Problem: Balloons span horizontal intervals [start, end]; an arrow shot at x bursts every balloon with start ≤ x ≤ end. Find the minimum…
- Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health…
- Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)? python def inter(s1, s2, s3): if len(s1) + len(s2)…
- Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every…
- Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1…