Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight.
Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight.
edges = [(4,'A','B'),(3,'A','C'),(1,'B','C'),(2,'B','D'),(4,'C','D'),(2,'D','E'),(5,'C','E')]
par = {c: c for c in 'ABCDE'}
def find(x):
while par[x] != x: x = par[x]
return x
total = 0
for w, u, v in sorted(edges):
ru, rv = find(u), find(v)
if ru != rv: par[ru] = rv; total += w
print(total)What is printed?- A. 9
- B. 16
- C. 8
- D. 5
Correct answer: C. 8
Sorted edges: B–C 1, B–D 2, D–E 2, A–C 3 (connects A); every later edge closes a cycle, so the MST weight is 1 + 2 + 2 + 3 = 8. Choosing A–B (4) instead of A–C gives 9, sorting in descending order builds the maximum spanning tree (16), and stopping after V − 2 edges leaves A out (5).
More Coding Interview Problems questions
- Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots…
- Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than…
- Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order. python def ways(coins, amt): dp…
- Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome. python…
- Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute…
- Problem: With e identical eggs, find the minimum number of drops that always identifies the critical floor of an f-floor building. The…