Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)).

Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)).
def mst(p):
    n = len(p); dist = [float('inf')] * n; dist[0] = 0
    used = [False] * n; total = 0
    for _ in range(n):
        u = min((d, i) for i, d in enumerate(dist) if not used[i])[1]
        used[u] = True; total += dist[u]
        for v in range(n):
            if not used[v]:
                dist[v] = min(dist[v], abs(p[u][0]-p[v][0]) + abs(p[u][1]-p[v][1]))
    return total
print(mst([(0, 0), (1, 5), (4, 1), (6, 6), (3, 3)]))
What is printed?
  1. A. 18
  2. B. 20
  3. C. 17
  4. D. 14

Correct answer: A. 18

With every pair connected, the O(n²) array version of Prim beats a heap (O(n² log n)). The tree uses (3,3)–(4,1) = 3, (3,3)–(1,5) = 4, (0,0)–(4,1) = 5 and (1,5)–(6,6) = 6, total 18, the same as Kruskal on all 10 edges.

More Coding Interview Problems questions

Exams that ask this topic