← DSA
MEDIUM

Min Cost to Connect All Points

PracticeNeetCode ↗LeetCode ↗

Given the coordinates of several points on a 2D plane, connect all of them so every point is reachable from every other, at minimum total cost — where the cost to connect two points is their Manhattan distance.

Example

Input points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output 20

Key Pointers

Step-by-Step Analysis

  1. Start from point 0 and push (0, 0) — meaning cost 0 to reach point index 0 — onto a min-heap.
  2. While fewer than n points are visited, pop the cheapest (cost, point) pair from the heap.
  3. If that point is already visited, skip it (a stale heap entry); otherwise mark it visited and add its cost to the running total.
  4. Push the Manhattan distance from the newly visited point to every still-unvisited point, and repeat until all n points are visited.

Complexity

Time: O(n² log n) — Space: O(n²)

Code

import heapq

def minCostConnectPoints(points: list[list[int]]) -> int:
    n = len(points)
    visited = set()
    min_heap = [(0, 0)]
    total_cost = 0

    while len(visited) < n:
        cost, i = heapq.heappop(min_heap)
        if i in visited:
            continue
        visited.add(i)
        total_cost += cost

        for j in range(n):
            if j not in visited:
                dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
                heapq.heappush(min_heap, (dist, j))

    return total_cost

Code Explanation

How the solution above works, piece by piece.

  1. This is a minimum spanning tree problem where every pair of points is an edge weighted by Manhattan distance. The code uses Prim's algorithm.
  2. The heap holds (cost, point) candidates for joining the tree; start with point 0 at cost 0.
  3. Pop the cheapest candidate. If the point is already in the tree, skip it (a cheaper edge got there first).
  4. Otherwise add it, pay its cost, and push edges from it to every point still outside the tree.
  5. Stop once all n points are in. With a heap this is O(n² log n); every pair is considered because the graph is complete.

Visual Walkthrough

Running it on points = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]:

Minimum spanning tree over five points43490(0,0)1(2,2)2(3,10)3(5,2)4(7,0)step 1: add 0–1 (cost 4)step 2: add 1–3 (cost 3)step 3: add 3–4 (cost 4)step 4: add 1–2 (cost 9)total = 20
Prim's algorithm grows one connected tree from point 0. At each step it adds the cheapest edge (Manhattan distance) from the tree to a point not yet in it. Four edges connect all five points for a total of 20.
chosen edge

Video Explanation

NeetCode — Prim's Algorithm (MST), LeetCode 1584