1010. Detect Cycle Using DSU

EasyGraphsDSUGraphCycle

Given an undirected graph with n nodes and a list of edges, determine whether it contains a cycle using a disjoint-set (union-find) structure. A cycle exists if an edge connects two nodes already in the same set. Return true or false. The input is JSON {n, edges}.

Input: JSON {n, edges}.

Output: Boolean — true or false.

Examples

Example 1
Input: {"n":4,"edges":[[0,1],[1,2],[2,0]]}
Output: true
Explanation: The third edge closes a cycle.
Example 2
Input: {"n":4,"edges":[[0,1],[1,2]]}
Output: false
Explanation: A tree has no cycle.
Example 3
Input: {"n":1,"edges":[]}
Output: false
Explanation: Single node.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →