[LeetCode] Minimum Time for K Connected Components

3608. Minimum Time for K Connected Components

You are given an integer n and an undirected graph with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [ui, vi, timei] indicates an undirected edge between nodes ui and vi that can be removed at timei.

You are also given an integer k.

Initially, the graph may be connected or disconnected. Your task is to find the minimum time t such that after removing all edges with time <= t, the graph contains at least k connected components.

Return the minimum time t.

A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
int uf[101010];
int find(int u) {
return uf[u] == u ? u : uf[u] = find(uf[u]);
}
bool uni(int u, int v) {
int pu = find(u), pv = find(v);
if(pu == pv) return false;
uf[pu] = uf[pv] = min(pu,pv);
return true;
}
public:
int minTime(int n, vector<vector<int>>& edges, int k) {
if(edges.size() == 0) return 0;
sort(begin(edges), end(edges), [](auto& a, auto& b) {
return a[2] < b[2];
});
iota(begin(uf), end(uf), 0);
int comp = n;
while(edges.size()) {
int x = edges.back()[2];
while(edges.size() and edges.back()[2] == x) {
int u = edges.back()[0], v = edges.back()[1], t = edges.back()[2];
edges.pop_back();
comp -= uni(u,v);
}
if(comp < k) return x;
}
return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/08/PS/LeetCode/minimum-time-for-k-connected-components/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.