Data Structures & AlgorithmsHardProduct Company SDE pattern
Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight?
Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight?
import heapq
edges = [(0, 1, 4), (0, 7, 8), (1, 2, 8), (1, 7, 11), (2, 3, 7), (2, 8, 2), (2, 5, 4),
(3, 4, 9), (3, 5, 14), (4, 5, 10), (5, 6, 2), (6, 7, 1), (6, 8, 6), (7, 8, 7)]
g = {i: [] for i in range(9)}
for u, v, w in edges: g[u].append((w, v)); g[v].append((w, u))
seen, pq, order, total = set(), [(0, 0)], [], 0
while pq:
w, u = heapq.heappop(pq)
if u in seen: continue
seen.add(u); order.append(u); total += w
for e in g[u]: heapq.heappush(pq, e)
print(order, total)- A. [0, 1, 7, 6, 5, 2, 8, 3, 4] 37
- B. [0, 1, 2, 8, 5, 6, 7, 3, 4] 39
- C. [0, 1, 2, 8, 5, 6, 7, 3, 4] 37
- D. [0, 7, 6, 5, 2, 8, 1, 3, 4] 37
Correct answer: C. [0, 1, 2, 8, 5, 6, 7, 3, 4] 37
Prim grows one tree, always adding the cheapest edge leaving it. After 0 (start) and 1 (weight 4), the cheapest crossing edges are 0–7 and 1–2, both 8; the heap holds (8, 7) and (8, 2), so the tie goes to vertex 2. Then 2–8 (2), 2–5 (4), 5–6 (2), 6–7 (1), 2–3 (7), 3–4 (9). Total 4 + 8 + 2 + 4 + 2 + 1 + 7 + 9 = 37 – the weight is the same whichever tied edge is taken. O(E log V).
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
- Kahn's topological sort with a FIFO queue (initial zero-indegree vertices in increasing order). What is printed? python from collections…
- Kruskal's algorithm: which edges are accepted, in order, for the graph below? python edges = sorted([(7, 'A', 'B'), (5, 'A', 'D'), (8…
- How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)? python base = 0…
- What is printed? (Tower of Hanoi: number of moves and the 5th move) python moves = [] def hanoi(n, a, b, c): if n == 0: return hanoi(n…
- What is printed? (recursion output order) python out = [] def f(n): if n == 0: return out.append(n) f(n - 1) out.append(n) f(3) print(out)
- Solve the recurrences numerically: how many 'work units' does each do for n = 64? python from functools import lrucache @lrucache(None)…