Min Cost to Connect All Points

35 min · minCostConnectPoints()

You need to wire every field sensor together, and every extra metre of cable costs money.

Each entry [x, y] in points is a distinct point on a 2D grid. Connecting [x1, y1] and [x2, y2] costs their Manhattan distance — the grid-walking distance |x1 - x2| + |y1 - y2|.

Return the smallest total cost that makes all points part of one connected structure. You may connect any pair, directly or through other points. The chosen connections form a minimum spanning tree (MST): a cheapest set of edges that connects every point without needing a cycle.

Constraints

  • 1 <= points.length <= 1_000
  • Every points[i] is [x, y] with -1_000_000 <= x, y <= 1_000_000.
  • All points are distinct.
  • The minimum total cost is less than 2^31.

Hints

See the hidden graph

Treat every point as a node and every pair as a possible weighted edge. You need an MST, but building all n(n - 1) / 2 edges costs quadratic memory.

Grow one connected region

Prim's algorithm starts from any point. Repeatedly add the outside point with the cheapest connection to the region already built.

Generate distances only when needed

Store, for each unchosen point, its cheapest distance to any chosen point. After adding one point, scan all unchosen points and update those values directly.

Follow-up

For millions of points, even O(n²) distance checks are too many. What geometric structure might help you avoid considering every possible pair?

Visible cases

Examples

Example 1

ready
Input
points = [
  [
    0,
    0
  ],
  [
    2,
    2
  ],
  [
    3,
    10
  ],
  [
    5,
    2
  ],
  [
    7,
    0
  ]
]
Expected
20
Why
the cheapest spanning connections have total Manhattan cost 20

Example 2

ready
Input
points = [
  [
    3,
    12
  ],
  [
    -2,
    5
  ],
  [
    -4,
    1
  ]
]
Expected
18
Why
connecting through [-2, 5] costs 12 + 6

Example 3

ready
Input
points = [
  [
    4,
    -7
  ]
]
Expected
0
Why
one point is already connected

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite