Data Structures & AlgorithmsHardTCS NQT · Accenture
Problem: Kruskal's algorithm with union-find is run on 5 nodes (0..4) with weighted edges (4,0,1), (1,1,2), (3,0,2), (2,2,3), (7,3,4), (5,1,4), given as (weight, u, v). What is the total MST weight?
Problem: Kruskal's algorithm with union-find is run on 5 nodes (0..4) with weighted edges (4,0,1), (1,1,2), (3,0,2), (2,2,3), (7,3,4), (5,1,4), given as (weight, u, v). What is the total MST weight?
def mst(n, edges):
p = list(range(n))
def f(x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
t = 0
for w, u, v in sorted(edges):
a, b = f(u), f(v)
if a != b:
p[a] = b
t += w
return t
print(mst(5, [(4, 0, 1), (1, 1, 2), (3, 0, 2), (2, 2, 3), (7, 3, 4), (5, 1, 4)]))What is printed?- A. 10
- B. 19
- C. 6
- D. 11
Correct answer: D. 11
Kruskal takes weights 1, 2, 3 and 5 in sorted order, skipping 4 (0–1 closes a cycle) and 7, for a total of 11. Taking the four lightest edges without a cycle check gives 10, sorting in descending order builds the maximum spanning tree (19), and stopping after three edges leaves node 4 out (6).
More Coding Interview Problems questions
- Problem: Count the subsets (including the empty subset) of {1, 2, 3, 4, 5, 6} whose sum is divisible by 3. python a = [1, 2, 3, 4, 5, 6]…
- Problem: How many integers x with 1 <= x <= 100 have no two adjacent equal decimal digits? Use the rule that a one-digit number always…
- Problem: What is the sum of all divisors of 360 = 2^3 3^2 5?
- Problem: Find the smallest positive x satisfying x ≡ 2 (mod 3), x ≡ 3 (mod 5) and x ≡ 2 (mod 7).
- Problem: Which pair (x, y) satisfies 240x + 46y = gcd(240, 46)?
- Problem: Cows must be placed in stalls at positions [1, 2, 4, 8, 9] so that the minimum distance between any two cows is as large as…