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
Minimum Spanning Tree - City Connection ProblemCity A(1,2)City B(7,3)City C(11,4)City D(5,6)Cost: 6Cost: 7Cost: 5Legend:Selected MST RoadsPossible Roads (not used)Total Cost: 6 + 7 + 5 = 18Prim's Algorithm:1. Start with City A2. Add cheapest connection: Aโ†’B (cost 7)3. Add cheapest to MST: Bโ†’C (cost 5)4. Add final connection: Aโ†’D (cost 6)Time: O(nยฒ) | Space: O(n)
Understanding the Visualization
1
Calculate All Distances
Find Manhattan distance between every pair of points
2
Start MST Construction
Pick any starting point and mark it as connected
3
Grow the Tree
Always add the cheapest edge connecting MST to a new point
4
Complete Connection
Continue until all points are connected with n-1 edges
Key Takeaway
๐ŸŽฏ Key Insight: MST problems require exactly n-1 edges to connect n points optimally. Prim's greedy approach of always choosing the cheapest available connection guarantees the minimum total cost.
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