Skip to content

Commit 83ab1ca

Browse files
committed
feat: Solve leetcode/leetcoding_challenge/2025/jan2025/week5/redundant_connection.cpp
1 parent 6aea6e8 commit 83ab1ca

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <algorithm>
2+
#include <vector>
3+
#include <queue>
4+
#include <set>
5+
#include <limits>
6+
#include <map>
7+
#include <unordered_set>
8+
#include <unordered_map>
9+
#include <iterator>
10+
#include <sstream>
11+
#include <iostream> // includes cin to read from stdin and cout to write to stdout
12+
using namespace std; // since cin and cout are both in namespace std, this saves some text
13+
14+
class Solution {
15+
private:
16+
vector<int> parents;
17+
vector<int> sizes;
18+
19+
int find(int x) {
20+
if (parents[x] != x) {
21+
parents[x] = find(parents[x]);
22+
}
23+
return parents[x];
24+
}
25+
26+
bool unionSet(int x, int y) {
27+
x = find(x);
28+
y = find(y);
29+
if (x == y) {
30+
// the edge is redundant
31+
// as the 2 nodes are already unioned
32+
return false;
33+
}
34+
35+
if (sizes[x] < sizes[y]) {
36+
int temp = x;
37+
x = y;
38+
y = temp;
39+
}
40+
41+
parents[y] = x;
42+
sizes[x] += sizes[y];
43+
return true;
44+
}
45+
46+
public:
47+
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
48+
int n = edges.size();
49+
vector<int> answer;
50+
51+
parents = vector<int>();
52+
for (int i = 0; i < n; ++i) {
53+
parents.push_back(i);
54+
}
55+
sizes = vector<int>(n, 1);
56+
57+
for (auto edge: edges) {
58+
auto a = edge[0];
59+
auto b = edge[1];
60+
if (!unionSet(a - 1, b - 1)) {
61+
answer = {a, b};
62+
}
63+
}
64+
65+
return answer;
66+
}
67+
};

0 commit comments

Comments
 (0)