CodingNodes / Advanced Graphs / Min Cost to Connect All Points System design Space play · ←→ step · R restart

Problem

You are given the coordinates of some points on a plane, points[i] = [x, y]. Wiring two points together costs their Manhattan distance, |x1 − x2| + |y1 − y2|.

Return the smallest total cost of wires that makes the points connected: between any two points there must be exactly one path of wires.

Constraints

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

Examples: pick one to animate

Solutions

TimeO(n² log n) SpaceO(n²)

Time: Every point that joins pushes a wire to each point still outside, so up to about n²/2 entries go through the heap, each push and pop costing log n².

Space: The heap can hold up to about n²/2 wires at once, because stale ones stay until they are popped.

Grow one tree from point 0. Keep a min-heap of (cost, point) wires that reach out of the tree. Pop the cheapest: if its point is already in the tree it is stale, skip it. Otherwise the point joins, its cost is added to the total, and a wire to every point still outside is pushed. The cheapest wire leaving a tree is always safe to take, so after n points have joined the total is the minimum. The code uses its own array heap (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.