Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Last Updated :
14 Dec, 2022
Check whether a given graph contains a cycle or not.
Example:
Input:

Output: Graph contains Cycle.
Input:

Output: Graph does not contain Cycle.
Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path Compression
We have already discussed union-find to detect cycle. Here we discuss find by path compression, where it is slightly modified to work faster than the original method as we are skipping one level each time we are going up the graph. Implementation of find function is iterative, so there is no overhead involved. Time complexity of optimized find function is O(log*(n)), i.e iterated logarithm, which converges to O(1) for repeated calls.
Refer this link for
Proof of log*(n) complexity of Union-Find
Explanation of find function:
Take Example 1 to understand find function:
(1)call find(8) for first time and mappings will be done like this:

It took 3 mappings for find function to get the root of node 8. Mappings are illustrated below:
From node 8, skipped node 7, Reached node 6.
From node 6, skipped node 5, Reached node 4.
From node 4, skipped node 2, Reached node 0.
(2)call find(8) for second time and mappings will be done like this:

It took 2 mappings to find function to get the root of node 8. Mappings are illustrated below:
From node 8, skipped node 5, node 6, and node 7, Reached node 4.
From node 4, skipped node 2, Reached node 0.
(3)call find(8) for third time and mappings will be done like this:

Finally, we see it took only 1 mapping for find function to get the root of node 8. Mappings are illustrated below:
From node 8, skipped node 5, node 6, node 7, node 4, and node 2, Reached node 0.
That is how it converges path from certain mappings to single mapping.
Explanation of example 1:
Initially array size and Arr look like:
Arr[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8}
size[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1}
Consider the edges in the graph, and add them one by one to the disjoint-union set as follows:
Edge 1: 0-1
find(0)=>0, find(1)=>1, both have different root parent
Put these in single connected component as currently they doesn't belong to different connected components.
Arr[1]=0, size[0]=2;
Edge 2: 0-2
find(0)=>0, find(2)=>2, both have different root parent
Arr[2]=0, size[0]=3;
Edge 3: 1-3
find(1)=>0, find(3)=>3, both have different root parent
Arr[3]=0, size[0]=3;
Edge 4: 3-4
find(3)=>1, find(4)=>4, both have different root parent
Arr[4]=0, size[0]=4;
Edge 5: 2-4
find(2)=>0, find(4)=>0, both have same root parent
Hence, There is a cycle in graph.
We stop further checking for cycle in graph.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX_VERTEX = 101;
int Arr[MAX_VERTEX];
int size[MAX_VERTEX];
void initialize(int n)
{
for (int i = 0; i <= n; i++) {
Arr[i] = i;
size[i] = 1;
}
}
int find(int i)
{
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]];
i = Arr[i];
}
return i;
}
void _union(int xr, int yr)
{
if (size[xr] < size[yr])
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
int isCycle(vector<int> adj[], int V)
{
for (int i = 0; i < V; i++) {
for (int j = 0; j < adj[i].size(); j++) {
int x = find(i);
int y = find(adj[i][j]);
if (x == y)
return 1;
_union(x, y);
}
}
return 0;
}
int main()
{
int V = 3;
initialize(V);
vector<int> adj[V];
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(2);
if (isCycle(adj, V))
cout << "Graph contains Cycle.\n";
else
cout << "Graph does not contain Cycle.\n";
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int MAX_VERTEX = 101;
static int []Arr = new int[MAX_VERTEX];
static int []size = new int[MAX_VERTEX];
static void initialize(int n)
{
for (int i = 0; i <= n; i++)
{
Arr[i] = i;
size[i] = 1;
}
}
static int find(int i)
{
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]];
i = Arr[i];
}
return i;
}
static void _union(int xr, int yr)
{
if (size[xr] < size[yr])
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
static int isCycle(Vector<Integer> adj[], int V)
{
for (int i = 0; i < V; i++)
{
for (int j = 0; j < adj[i].size(); j++)
{
int x = find(i);
int y = find(adj[i].get(j));
if (x == y)
return 1;
_union(x, y);
}
}
return 0;
}
public static void main(String[] args)
{
int V = 3;
initialize(V);
Vector<Integer> []adj = new Vector[V];
for(int i = 0; i < V; i++)
adj[i] = new Vector<Integer>();
adj[0].add(1);
adj[0].add(2);
adj[1].add(2);
if (isCycle(adj, V) == 1)
System.out.print("Graph contains Cycle.\n");
else
System.out.print("Graph does not contain Cycle.\n");
}
}
|
Python3
def initialize(n):
global Arr, size
for i in range(n + 1):
Arr[i] = i
size[i] = 1
def find(i):
global Arr, size
while (Arr[i] != i):
Arr[i] = Arr[Arr[i]]
i = Arr[i]
return i
def _union(xr, yr):
global Arr, size
if (size[xr] < size[yr]):
Arr[xr] = Arr[yr]
size[yr] += size[xr]
else:
Arr[yr] = Arr[xr]
size[xr] += size[yr]
def isCycle(adj, V):
global Arr, size
for i in range(V):
for j in range(len(adj[i])):
x = find(i)
y = find(adj[i][j])
if (x == y):
return 1
_union(x, y)
return 0
MAX_VERTEX = 101
Arr = [None] * MAX_VERTEX
size = [None] * MAX_VERTEX
V = 3
initialize(V)
adj = [[] for i in range(V)]
adj[0].append(1)
adj[0].append(2)
adj[1].append(2)
if (isCycle(adj, V)):
print("Graph contains Cycle.")
else:
print("Graph does not contain Cycle.")
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MAX_VERTEX = 101;
static int []Arr = new int[MAX_VERTEX];
static int []size = new int[MAX_VERTEX];
static void initialize(int n)
{
for (int i = 0; i <= n; i++)
{
Arr[i] = i;
size[i] = 1;
}
}
static int find(int i)
{
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]];
i = Arr[i];
}
return i;
}
static void _union(int xr, int yr)
{
if (size[xr] < size[yr])
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
static int isCycle(List<int> []adj, int V)
{
for (int i = 0; i < V; i++)
{
for (int j = 0; j < adj[i].Count; j++)
{
int x = find(i);
int y = find(adj[i][j]);
if (x == y)
return 1;
_union(x, y);
}
}
return 0;
}
public static void Main(String[] args)
{
int V = 3;
initialize(V);
List<int> []adj = new List<int>[V];
for(int i = 0; i < V; i++)
adj[i] = new List<int>();
adj[0].Add(1);
adj[0].Add(2);
adj[1].Add(2);
if (isCycle(adj, V) == 1)
Console.Write("Graph contains Cycle.\n");
else
Console.Write("Graph does not contain Cycle.\n");
}
}
|
Javascript
<script>
var MAX_VERTEX = 101;
var Arr = Array(MAX_VERTEX).fill(0);
var size = Array(MAX_VERTEX).fill(0);
function initialize(n)
{
for (var i = 0; i <= n; i++) {
Arr[i] = i;
size[i] = 1;
}
}
function find(i)
{
while (Arr[i] != i)
{
Arr[i] = Arr[Arr[i]];
i = Arr[i];
}
return i;
}
function _union(xr, yr)
{
if (size[xr] < size[yr])
{
Arr[xr] = Arr[yr];
size[yr] += size[xr];
}
else
{
Arr[yr] = Arr[xr];
size[xr] += size[yr];
}
}
function isCycle(adj, V)
{
for (var i = 0; i < V; i++) {
for (var j = 0; j < adj[i].length; j++) {
var x = find(i);
var y = find(adj[i][j]);
if (x == y)
return 1;
_union(x, y);
}
}
return 0;
}
var V = 3;
initialize(V);
var adj = Array.from(Array(V), ()=>Array());
adj[0].push(1);
adj[0].push(2);
adj[1].push(2);
if (isCycle(adj, V))
document.write("Graph contains Cycle.<br>");
else
document.write("Graph does not contain Cycle.<br>");
</script>
|
Output
Graph contains Cycle.
Complexity Analysis:
- Time Complexity(Find) : O(log*(n))
- Time Complexity(union) : O(1)
- Auxiliary Space: O(Max_Vertex)
Similar Reads
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Check whether a given graph contains a cycle or not. Example: Input: Output: Graph contains Cycle. Input: Output: Graph does not contain Cycle. Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path CompressionWe have already discussed union-find to detect cycle. Here we discuss find by
13 min read
Union By Rank and Path Compression in Union-Find Algorithm
In the previous post, we introduced union find algorithm and used it to detect cycles in a graph. We used the following union() and find() operations for subsets. C/C++ Code // Naive implementation of find int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]);
15+ min read
Disjoint Set Union (Randomized Algorithm)
A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find. The disjoint set union algorithm allows you to perform the following operations efficiently: Fin
15+ min read
Introduction to Divide and Conquer Algorithm
Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the main problem into subproblems, solving them individually and then merging them to find solution to the original problem. In this article, we are going to discuss how Divide and Conquer Algorithm is hel
12 min read
Union and Intersection of Two Sorted Arrays - Complete Tutorial
Union of two arrays is an array having all distinct elements that are present in either array whereas Intersection of two arrays is an array containing distinct common elements between the two arrays. In this post, we will discuss about Union and Intersection of sorted arrays. To know about union an
6 min read
Extended Mo's Algorithm with ≈ O(1) time complexity
Given an array of n elements and q range queries (range sum in this article) with no updates, task is to answer these queries with efficient time and space complexity. The time complexity of a range query after applying square root decomposition comes out to be O(?n). This square-root factor can be
15+ min read
Union and Intersection Operation On Graph
In graph theory, the data/objects belong to the same group but each piece of data differs from one other. In this article, we will see union and intersection operations on the graph. Union Operation Let G1(V1, E1) and G2(V2, E2) be two graphs as shown below in the diagram. The union of G1 and G2 is
2 min read
MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
Let us consider the following problem to understand MO's Algorithm.We are given an array and a set of query ranges, we are required to find the sum of every query range. Example: Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; query[] = [0, 4], [1, 3] [2, 4] Output: Sum of arr[] elements in range [0, 4]
15+ min read
Introduction to Branch and Bound - Data Structures and Algorithms Tutorial
Branch and bound algorithms are used to find the optimal solution for combinatory, discrete, and general mathematical optimization problems. A branch and bound algorithm provide an optimal solution to an NP-Hard problem by exploring the entire search space. Through the exploration of the entire sear
13 min read
Minimize Increments for Equal Path Sum from Root to Any Leaf
Given arrays arr[] and edges[] where edges[i] denotes an undirected edge from edges[i][0] to edges[i][1] and arr[i] represents the value of the ith node. The task is to find the minimum number of increments by 1 required for any node, such that the sum of values along any path from the root to a lea
10 min read
Compress a Binary Tree into an integer diagonally
Given a Binary Tree consisting of N nodes, the task is to first compress the tree diagonally to get a list of integers and then, again compress the list to get a single integer using the following operations: When a tree is compressed diagonally, its value in binary representation gets compressed.Co
10 min read
Tarjan's off-line lowest common ancestors algorithm
Prerequisite : LCA basics, Disjoint Set Union by Rank and Path CompressionWe are given a tree(can be extended to a DAG) and we have many queries of form LCA(u, v), i.e., find LCA of nodes ‘u’ and ‘v’.We can perform those queries in O(N + QlogN) time using RMQ, where O(N) time for pre-processing and
15+ min read
Union and Intersection of two Linked List using Merge Sort
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two lists contains distinct node values. Note: The order of elements in output lists doesn't matter. Examples: Input: head1: 10 -> 15
15+ min read
Union and Intersection of two Linked List using Hashing
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.Note: The order of elements in output lists doesn’t matter. Examples: Input:head1 : 10 -
10 min read
Time and Space Complexity Analysis of Kruskal Algorithm
Kruskal's algorithm is a popular algorithm for finding the Minimum Spanning Tree (MST) of a connected, undirected graph. The time complexity of Kruskal's algorithm is O(E log E), where E is the number of edges in the graph. The space complexity of Kruskal's algorithm is O(V + E), where V is the numb
2 min read
Union and Intersection of Two Unsorted Arrays - Complete Tutorial
Union of two arrays is an array having all distinct elements that are present in either array whereas Intersection of two arrays is an array containing distinct common elements between the two arrays. In this post, we will discuss about Union and Intersection of unsorted arrays. To know about union
6 min read
Comparison between Shortest Path Algorithms:
Finding the shortest way is becoming more important in a world where time and distance matter. There are multiple shorted path algorithms exists. Therefore, in this article, we will compare the shortest path algorithms on the basis of their complexity and their performance, which will help us to use
4 min read
Klee's Algorithm (Length Of Union Of Segments of a line)
Given starting and ending positions of segments on a line, the task is to take the union of all given segments and find length covered by these segments.Examples: Input : segments[] = {{2, 5}, {4, 8}, {9, 12}} Output : 9 Explanation: segment 1 = {2, 5} segment 2 = {4, 8} segment 3 = {9, 12} If we ta
9 min read
Time-Space Trade-Off in Algorithms
In this article, we will discuss Time-Space Trade-Off in Algorithms. A tradeoff is a situation where one thing increases and another thing decreases. It is a way to solve a problem in: Either in less time and by using more space, orIn very little space by spending a long amount of time.The best Algo
8 min read