You get points, a list of distinct spots on a grid, each written as [x, y]. Linking two spots costs their Manhattan distance: the gap in x plus the gap in y, |x1 − x2| + |y1 − y2|.
Choose links so that every spot can reach every other spot, and return the smallest total cost that does it. A single spot needs no links and costs 0.
Example 1
Input: points = [[0, 0], [2, 1], [5, 0], [1, 5]] Output: 12 Why: link [0,0]–[2,1] (3), [2,1]–[5,0] (4) and [2,1]–[1,5] (5)
2 more examples and the constraints
Example 2
Input: points = [[-3, 2], [4, -1]] Output: 10 Why: one link: 7 across plus 3 down
Example 3
Input: points = [[6, 6]] Output: 0 Why: one point is already connected
Constraints
- 1 ≤ number of points ≤ 1,000
- −1,000,000 ≤ x, y ≤ 1,000,000
- No two points are the same
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Kruskal: sort every edgeO(n² log n)
- Prim with a distance arrayO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 points | Verdict |
|---|---|---|---|
| Kruskal: sort every edge | O(n² log n) | Passes; builds 500,000 edges | |
| Prim with a distance array | O(n²) | Best; no edge list at all |
n = number of points; there are n(n − 1)/2 possible links.
Edge cases to test
- One point. [[6, 6]] costs 0: there is nothing to link.
- Two points. The answer is just their distance.
- Points on one line. The best links join neighbours along the line, never the two far ends.
- Far corners. [-1,000,000, -1,000,000] to [1,000,000, 1,000,000] costs 4,000,000, which still fits in a 32-bit int.
Common mistakes
- Using straight-line distance instead of |dx| + |dy|.
- In Kruskal, adding an edge whose ends are already connected, which makes a loop and overcounts.
- In Prim, forgetting to skip points already in the tree when picking the next one.
How to talk through it
- 1Clarify. Is the cost Manhattan distance? Can points repeat? What is the answer for a single point?
- 2Name the graph. Points are nodes, every pair is an edge, and the goal is a minimum spanning tree.
- 3Give Kruskal. Sort the edges, union the ends unless they are already joined; O(n² log n) with O(n²) memory.
- 4Move to Prim. The graph is dense, so an O(n²) array-based Prim avoids building the edge list at all.
- 5Test out loud. Run one point, two points, and three points on a line.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?