Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Connect every point at the least cost

Medium · Target 25 minutes · Graphs · Type asked atAmazonMicrosoft

You are given distinct points on a plane, points[i] = [x, y]. Connecting points i and j costs their Manhattan distance |xi − xj| + |yi − yj|. Return the minimum total cost to make every point reachable from every other: each pair must be joined by exactly one path of connections.

Examples

InputOutputWhy
points = [[0,0],[2,2],[3,10],[5,2],[7,0]]20Connect (0,0)–(2,2), (2,2)–(5,2), (5,2)–(7,0) and (2,2)–(3,10): 4 + 3 + 4 + 9.
points = [[3,12],[-2,5],[-4,1]]18(-4,1)–(-2,5) costs 6, (-2,5)–(3,12) costs 12.
points = [[0,0]]0One point needs no connection.

Constraints

  • 1 ≤ points.length ≤ 1000
  • −10⁶ ≤ x, y ≤ 10⁶
  • All points are distinct

Hints

Hint 1

Exactly one path between every pair means the connections form a tree: you want a minimum spanning tree.

Hint 2

Every pair of points is a possible edge: about n²/2 of them. Sorting them all for Kruskal is possible but heavy.

Hint 3

Prim without a heap: keep for each point outside the tree its cheapest connection to the tree, pick the smallest, then update the others. O(n²) and no edge list.

Where people lose marks

  • Building all n²/2 edges and sorting them: correct, but 500,000 edges for n = 1000 and much slower.
  • Using Euclidean distance instead of Manhattan distance.
  • Overflow: a single distance can reach 4 · 10⁶ and the total 4 · 10⁹, beyond a 32-bit integer.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.