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?- A. 18
- B. 20
- C. 17
- 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
- Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of…
- Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor). python par = [-1, 0, 0, 1, 1, 2, 3, 3, 4…
- A COMPLETE binary tree has n nodes. Counting them by comparing the leftmost and rightmost depths at each node and recursing into only one…
- Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder. python def postfrompre(pre): i, out = 0…
- Problem: For every node of a tree, compute the sum of distances to all other nodes in O(n) with re-rooting: ans[child] = ans[parent] −…
- Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a…