Open In App

Check if a cycle of length 3 exists or not in a graph that satisfy a given condition

Given an array Arr of N integers representing the nodes of a graph. The edges are defined between those pairs whose bitwise AND is not equal to zero. The task is to find if there exists a cycle of length 3 or not in the graph.
Examples: 
 

Input: Arr[] = {26, 33, 35, 40, 50} 
Output: Yes
A cycle exists between 26, 33 and 50.
Input: Arrr[] = {17, 142, 243, 300} 
Output: No
 

 

Naive Approach: 
Run a nested loop and check for each pair whether there exists an edge between them(if their bitwise AND value is non-zero). Thus, we form the entire graph and check if a cycle exists in this graph by using any of cycle detection methods.
Efficient Approach: 
 

 

Arr[] = {26, 33, 35, 40, 50}
The 2D array is as following 
bi = [ 
[0 1 0 1 1 0 0 0], 
[1 0 0 0 0 1 0 0], 
[1 1 0 0 0 1 0 0], 
[0 0 0 1 0 1 0 0], 
[0 1 0 0 1 1 0 0], 

bi[0][1], bi[2][1] and bi[4][1] are equal to 1. This implies that bitwise AND value of the following pairs (Arr[0], Arr[2]), (Arr[2], Arr[4]), (Arr[0], Arr[4]) are non-zero. These 3 edges form a cycle.
 

Below is the implementation of the above approach: 
 

Code block

Output: 
Yes

 

Article Tags :