-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet202.cpp
More file actions
35 lines (35 loc) · 1.11 KB
/
leet202.cpp
File metadata and controls
35 lines (35 loc) · 1.11 KB
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
32
33
34
35
class Solution {
vector<int> parent;
vector<int> rank;
int find(int i) {
if (parent[i] != i)
parent[i] = find(parent[i]); // Path compression
return parent[i];
}
void join(int u, int v) {
int rootU = find(u), rootV = find(v);
if (rootU != rootV) {
// Union by rank to balance trees
if (rank[rootU] > rank[rootV]) parent[rootV] = rootU;
else if (rank[rootU] < rank[rootV]) parent[rootU] = rootV;
else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size();
parent.resize(n + 1);
rank.resize(n + 1, 0);
// Initialize each node as its own parent
for (int i = 1; i <= n; i++) parent[i] = i;
for (auto& edge : edges) {
int u = edge[0], v = edge[1];
if (find(u) == find(v)) return edge; // Cycle detected!
join(u, v); // Merge sets
}
return {}; // Unreachable for valid inputs
}
};