#3608
Minimum Time for K Connected Components
MediumBinary SearchUnion-FindGraph TheorySortingBinary SearchUnion-Find
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m log m + m α(n)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(m log m + m α(n))Space O(n)
Use binary search on time to efficiently find the minimum time t where the graph has at least k components after edge removals.
⚙️
Algorithm
3 steps- 1Step 1: Sort edges by time.
- 2Step 2: Use binary search on time from 0 to max edge time.
- 3Step 3: For mid time, use Union-Find to count components and adjust search range based on the count.
solution.py14 lines
1def minTime(n, edges, k):
2 edges.sort(key=lambda x: x[2])
3 left, right = 0, edges[-1][2]
4 while left < right:
5 mid = (left + right) // 2
6 uf = UnionFind(n)
7 for u, v, time in edges:
8 if time <= mid:
9 uf.union(u, v)
10 if uf.count() >= k:
11 right = mid
12 else:
13 left = mid + 1
14 return leftℹ
Complexity note: Sorting edges takes O(m log m), and Union-Find operations take O(m α(n)), where α is the inverse Ackermann function.
- 1Binary search reduces the number of checks needed.
- 2Union-Find efficiently counts connected components.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.