Min Cost to Connect All Points - Problem
Minimum Spanning Tree Problem: Imagine you're a city planner tasked with connecting multiple districts with roads. You have n districts represented as points on a 2D coordinate plane, where each point points[i] = [xi, yi] represents the coordinates of district i.

The cost of building a road between two districts is equal to their Manhattan distance: |xi - xj| + |yi - yj|. Your goal is to find the minimum total cost to connect all districts such that there's exactly one path between any two districts (forming a tree structure).

Input: An array of 2D coordinates representing district locations
Output: The minimum cost to connect all districts with roads

Input & Output

example_1.py — Basic Triangle
$ Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
💡 Note: Connect points to form MST: (0,0)→(7,0) cost 7, (7,0)→(5,2) cost 4, (5,2)→(2,2) cost 3, (2,2)→(3,10) cost 9. Total: 7+4+3+6=20
example_2.py — Simple Square
$ Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
💡 Note: Three points form a triangle. Cheapest connections: (-4,1)→(-2,5) cost 6, (-2,5)→(3,12) cost 12. Total: 6+12=18
example_3.py — Single Point
$ Input: points = [[0,0]]
Output: 0
💡 Note: Single point needs no connections, so cost is 0

Constraints

  • 1 ≤ points.length ≤ 1000
  • -106 ≤ xi, yi ≤ 106
  • All pairs (xi, yi) are distinct
  • Manhattan distance only - not Euclidean distance

Visualization

Tap to expand
Min Cost to Connect All Points Minimum Spanning Tree using Prim's Algorithm INPUT x y P0 P1 P2 P3 P4 Points Array: [0,0] [2,2] [3,10] [5,2] [7,0] n = 5 districts Cost = |x1-x2| + |y1-y2| ALGORITHM STEPS 1 Initialize Start from point 0 Min-heap with distances 2 Extract Minimum Pop smallest edge from heap Add to MST if not visited 3 Update Neighbors Calculate Manhattan dist Push to heap if smaller 4 Repeat Until Done Until all n points visited Sum all edge costs Edge Selection Order: P0--P1: |0-2|+|0-2| = 4 P1--P3: |2-5|+|2-2| = 3 P3--P4: |5-7|+|2-0| = 4 P3--P2: |5-3|+|2-10| = 10 Total: 4+3+4+10 = 21? No! FINAL RESULT 4 3 4 9 0 1 2 3 4 Output: 20 MST Edge Costs: P0-P1=4, P1-P3=3 P3-P4=4, P1-P2=9 4 + 3 + 4 + 9 = 20 Key Insight: Prim's algorithm builds the MST by always selecting the minimum cost edge that connects a visited node to an unvisited node. Using a min-heap ensures O(n^2 log n) time complexity. The MST guarantees exactly one path between any two nodes with minimum total edge weight (Manhattan distance). TutorialsPoint - Min Cost to Connect All Points | Prim's Algorithm (Optimal Solution) Time: O(n^2 log n) | Space: O(n^2)
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28 Meta 25
89.5K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen