[LeetCode] Redundant Connection

684. Redundant Connection

In this problem, a tree is an undirected graph that is connected and has no cycles.

You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.

Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
unordered_map<int, int> group;
int getGroup(int n) {
return group.count(n) ? _getGroup(n) : group[n] = n;
}

int _getGroup(int n) {
return n == group[n] ? n : group[n] = _getGroup(group[n]);
}
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
for(auto edge : edges) {
if(getGroup(edge.front()) ^ getGroup(edge.back())) {
group[getGroup(edge.front())] = group[getGroup(edge.back())] = min(group[getGroup(edge.front())], group[getGroup(edge.back())]);
} else {
return edge;
}
}
return {-1, -1};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/25/PS/LeetCode/redundant-connection/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.