The Climax: Unveiling the Existence of a Cycle
The suspense peaks as we look at the last remaining road, connecting intersections 3
and 4
. These intersections are in separate neighborhoods, so once again, it's time for a merge.
Step 1: The Final Merge with Union(3, 4)
We're merging the neighborhoods of 3
and 4
. Given that 3
is already the head of a large neighborhood {0, 1, 2, 3}
, this merge will add 4
to this expanding community.
The Last Update on the Investigation Board
Step 2: Interpreting the Final State of the Parent Array
By updating the value under 3
to 4
, we signify that 4
is now the head of this mega-neighborhood, representing the union set {0, 1, 2, 3, 4}
. It's as if 4
has assumed the role of the ultimate community leader, consolidating all the smaller communities into one.
Step 3: The Moment of Truth
Now, let's pay attention to the last edge that connects 3
and 4
. According to our parent array, both intersections are part of the same large neighborhood. Using our find
operation, we discover:
1Find(3) = 4
2Find(4) = 4
The results are clear as day. Both 3
and 4
are part of the same neighborhood, which means we've found a cycle!

The Final Verdict: A Cycle Detected!
That's our "Aha!" moment! Finding that both elements belong to the same group confirms the presence of a cycle in this graph. Our detective journey using the Union-Find algorithm has reached its pinnacle, successfully revealing a loop in our network of roads.
xxxxxxxxxx
}
// Initialize the parent array to represent isolated neighborhoods.
const parent = [0, 1, 2, 3, 4];
​
// Define the find function to identify the 'root' or 'parent' of each neighborhood.
function find(vertex) {
if (parent[vertex] === vertex) {
return vertex;
}
return find(parent[vertex]);
}
​
// Define the Union function to merge neighborhoods.
function union(vertex1, vertex2) {
const root1 = find(vertex1);
const root2 = find(vertex2);
parent[root1] = root2;
}
​
// Merging previous neighborhoods.
union(0, 1);
union(1, 2);
union(2, 3);
​
// Investigate the last remaining road connecting intersections 3 and 4.
union(3, 4);
​
// Display the updated parent array.
console.log(`Updated Parent Array: ${parent}`);
​