Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order).
Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order).
edges = [(7,0,1),(5,0,3),(8,1,2),(9,1,3),(7,1,4),(5,2,4),(15,3,4),(6,3,5),(8,4,5),(11,4,6),(9,5,6)]
par = list(range(7))
def f(x):
while par[x] != x: x = par[x]
return x
tot = 0
for w, u, v in sorted(edges, reverse=True):
if f(u) != f(v): par[f(u)] = f(v); tot += w
print(tot)What is printed?- A. 39
- B. 59
- C. 52
- D. 60
Correct answer: B. 59
Take the heaviest edges that do not form a cycle: 15 (3–4), 11 (4–6), 9 (1–3), 9 (5–6), 8 (1–2), 7 (0–1) — six edges joining all 7 nodes, total 59. A minimum spanning tree on the same graph weighs 39.
More Coding Interview Problems questions
- Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford. python…
- Problem: Topological order produced by DFS (append a node after all its descendants, then reverse). python g = {0: [2, 1], 1: [3], 2: [3…
- Problem: Maximum bipartite matching between workers (left) and jobs (right) with Kuhn's augmenting-path algorithm. python adj = {0: [0…
- Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths). python from collections import deque cap = [[0]6 for…
- Problem: Does an undirected connected graph have an Euler path / Euler circuit? (count odd-degree vertices) python from collections import…
- Problem: Count Hamiltonian paths (ordered sequences visiting every vertex once) in a small undirected graph with bitmask DP. python n = 5…