# Creative solving of searching redundant connection in graph

I am trying to solve problem in leetcode: https://leetcode.com/problems/redundant-connection/description/ *finding redundant connection in undirected graph

And now I am writing a solution, inpired by Kruskal's algorithm: https://en.wikipedia.org/wiki/Disjoint-set_data_structure#/media/File:UnionFindKruskalDemo.gif

In short: I just add vertices in sets if I find a pair, when both vertices exist in set then it is an additional edge...

var findRedundantConnection = function(edges) {
let sets = [];
for (let i = 0; i < edges.length; i++) {
//find connections of each vertices in edge
let check_0_indexes = [];
let check_1_indexes = [];
for (let j = 0; j < sets.length; j++) {
if (sets[j]&&sets[j].includes(edges[i])) { //if vertices exist in sets
check_0_indexes.push(j);
} else if (sets[j]&&sets[j].includes(edges[i])) {
check_1_indexes.push(j);
}
}
check_0_indexes.map(el=>{
if(sets[el].includes(edges[i])){ //check first vertice: if pair exist in set
} else {
sets[el].push(edges[i]);
}
});
check_1_indexes.map(el=>{
if(sets[el].includes(edges[i])){
additionals.push(edges[i]);    //check second vertice: if pair exist in set
} else {
sets[el].push(edges[i]);
}
});
if(!check_0_indexes.length&&!check_1_indexes.length){
//if both vertices not in sets
sets.push([]); //create new set and add vertices
sets[sets.length-1].push(edges[i]);
sets[sets.length-1].push(edges[i]);
}
}
};


*JavaScript

But in this case: edges = [[3,7],[1,4],[2,8],[1,6],[7,9],[6,10],[1,7],[2,3],[8,9],[5,9]] I do not know how to catch loop ( (8,9) and (7,9) ) Any ideas about it?

• Are you saying that your algorithm does not work for the graph shown in the figure? Jun 9 at 10:08
• @InuyashaYagami yep, not working, when it have found (8,9) it will not add it in additional. i tried add it with finding similiar patterns between sets, but it is was a very complex way and in different cases it made worse Jun 9 at 10:41

For edge $$(2,3)$$, only $$3$$ is getting added to the existing set $$\{2,8\}$$. And, only $$2$$ is getting added to existing set $$\{3,7,9, \dotsc\}$$.
You should also add all the elements of the set $$\{2,8\}$$ to $$\{3,7,9, \dotsc\}$$ and vice-versa. Note that you have to merge the two sets $$\{2,8\}$$ to $$\{3,7,9,\dotsc\}$$ into one.