The Wayback Machine - https://web.archive.org/web/20210712201021/https://www.geeksforgeeks.org/check-if-a-cycle-of-length-3-exists-or-not-in-a-graph-that-satisfy-a-given-condition/
Skip to content
Related Articles

Related Articles

Improve Article
Check if a cycle of length 3 exists or not in a graph that satisfy a given condition
  • Last Updated : 13 May, 2021

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

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :