Open In App

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

Last Updated : 13 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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: 
 

  • A cycle is formed by joining at least 3 edges.
  • The idea is to make a 2D array where i-th row stores the binary value of Arr[i].
  • Next, loop in column-wise fashion and check if there exists a column where the number of 1’s is at least 3.
    • If so, it implies that there exists a cycle in the graph.
    • If no such column exists, it implies that there is no cycle in the graph.

 

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

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads