#1584
Min Cost to Connect All Points
MediumArrayUnion-FindGraph TheoryMinimum Spanning TreeGraph TheoryMinimum Spanning TreePriority Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a Minimum Spanning Tree (MST) algorithm like Prim's or Kruskal's. This approach efficiently connects all points with the minimum cost by focusing on edges with the lowest weights.
⚙️
Algorithm
3 steps- 1Step 1: Use a priority queue to store edges based on their Manhattan distance.
- 2Step 2: Start from an arbitrary point and add its edges to the queue.
- 3Step 3: Continuously extract the minimum edge from the queue and add the corresponding point to the MST until all points are connected.
solution.py24 lines
1import heapq
2
3class Solution:
4 def minCostConnectPoints(self, points):
5 n = len(points)
6 visited = [False] * n
7 min_heap = [(0, 0)] # (cost, point index)
8 total_cost = 0
9 edges_used = 0
10
11 while edges_used < n:
12 cost, u = heapq.heappop(min_heap)
13 if visited[u]:
14 continue
15 visited[u] = True
16 total_cost += cost
17 edges_used += 1
18
19 for v in range(n):
20 if not visited[v]:
21 distance = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1])
22 heapq.heappush(min_heap, (distance, v))
23
24 return total_costℹ
Complexity note: The time complexity is O(n log n) due to the priority queue operations. The space complexity is O(n) because we store the visited status of each point and the priority queue.
- 1Understanding the properties of Minimum Spanning Trees is crucial for solving connection problems.
- 2Using efficient data structures like priority queues can significantly reduce the time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.