</>

1584. Min Cost to Connect All Points

Medium NeetCode 150
Advanced Graphs Time O(N^2) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Advanced Graphs
Time
O(N^2)
Space
O(N)

Standard Solution (C++)

SummaryGiven a set of 2D points, find the minimum total Manhattan distance needed to build a spanning tree that connects every point to the network. Return that minimum total cost.

Approach
  • Model the problem as finding a Minimum Spanning Tree (MST) on a complete graph where edge weights are Manhattan distances between pairs of points.
  • Use Prim's algorithm with an O(n²) dense-graph formulation: maintain a minDist array tracking the cheapest known edge connecting each unvisited node to the current MST.
  • At each of n iterations, greedily pick the unvisited node with the smallest minDist, add its cost to the answer, mark it visited, then relax all remaining nodes against this newly added node.
  • This avoids explicitly enumerating all O(n²) edges upfront; the implicit edge weight is computed on-the-fly, keeping both time and space at O(n²) and O(n) respectively.
#include <vector>
#include <cmath>
#include <climits>
#include <algorithm>
using namespace std;

class Solution {
public:
    int minCostConnectPoints(vector<vector<int>>& points) {
        int n = points.size();

        // minDist[i] = cheapest edge connecting node i to the current MST
        vector<int> minDist(n, INT_MAX);
        vector<bool> inMST(n, false);

        minDist[0] = 0;           // start growing MST from node 0
        int totalCost = 0;

        for (int iter = 0; iter < n; ++iter) {
            // Pick the cheapest unvisited node
            int u = -1;
            for (int i = 0; i < n; ++i) {
                if (!inMST[i] && (u == -1 || minDist[i] < minDist[u]))
                    u = i;
            }

            inMST[u] = true;
            totalCost += minDist[u];

            // Relax neighbors: update their best known connection to the MST
            for (int v = 0; v < n; ++v) {
                if (!inMST[v]) {
                    int dist = abs(points[v][0] - points[u][0])
                             + abs(points[v][1] - points[u][1]);
                    minDist[v] = min(minDist[v], dist);
                }
            }
        }

        return totalCost;
    }
};
Time O(n^2) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int minCostConnectPoints(vector<vector<int>>& points) {
        int cost=0;
        int n=points.size();

        vector<bool> visited(n, false);
        vector<int> dist(n, INT_MAX);
 
        // start from any point
        dist[0]=0;
        int count=0; // node count

        while(count<n){
            int u=-1;
            int min_dist=INT_MAX;

            for(int i=0; i<n; ++i){
                if(!visited[i] && dist[i]<min_dist){
                    u=i;
                    min_dist=dist[i];
                }
            }

            if(u==-1){
                break;
            }

            visited[u]=true;
            cost+=min_dist;
            ++count;

            // update dist
            for(int v=0; v<n; ++v){
                if(!visited[v]){
                    int d=abs(points[v][0]-points[u][0])+abs(points[v][1]-points[u][1]);
                    dist[v]=min(dist[v], d);
                }
            }
        }

        return cost;

    }
};

// Time Complexity: O(N^2)
// Space Complexity: O(N)
Time O(N^2) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern