Problem description:

Union find is frequently used in graph problem. Pretty useful in cycle detection.

Solution:

reference:
https://www.geeksforgeeks.org/union-find/
https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf