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 pair 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 method.

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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Maximum numner of bits in Arr[i]
#define MAX 64
  
// Function to check if a cycle
// exists in the given graph
void checkCycle(int ar[], int n)
{
    int bi[n][MAX] = { 0 }, size;
    bool flag = false;
  
    // storing the given ar[i] in
    // binary in the array
    // where bi[i] is the
    // binary value of ar[i]
    for (int i = 0; i < n; i++) {
        size = 0;
        while (ar[i] != 0) {
            bi[i][size++] = ar[i] % 2;
            ar[i] = ar[i] / 2;
        }
    }
  
    // Checking if any column
    // contains at least 3 1's
    for (int i = 0; i < MAX; i++) {
        int ctr = 0;
        for (int j = 0; j < n; j++) {
            if (bi[j][i] == 1)
                ctr = ctr + 1;
        }
        if (ctr >= 3) {
  
            // If number of 1's is more than
            // 3, set flag to true and break
            flag = true;
            break;
        }
    }
  
    // if flag is true, it implies
    // that graph contains a cycle
    if (flag)
        cout << "Yes";
    // if flag is false, no cycle
    // is there in the graph
    else
        cout << "No";
}
  
// Driver code
int main()
{
    int ar[] = { 26, 33, 35, 40, 50 };
    int n = sizeof(ar) / sizeof(ar[0]);
    checkCycle(ar, n);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// the above approach
import java.io.*;
  
class GFG 
{
      
// Maximum numner of bits in Arr[i]
static int MAX = 64;
  
// Function to check if a cycle
// exists in the given graph
static void checkCycle(int ar[], int n)
{
    int bi[][] = new int[n][MAX];
    int size;
    boolean flag = false;
  
    // storing the given ar[i] in
    // binary in the array
    // where bi[i] is the
    // binary value of ar[i]
    for (int i = 0; i < n; i++) 
    {
        size = 0;
        while (ar[i] != 0
        {
            bi[i][size++] = ar[i] % 2;
            ar[i] = ar[i] / 2;
        }
    }
  
    // Checking if any column
    // contains at least 3 1's
    for (int i = 0; i < MAX; i++)
    {
        int ctr = 0;
        for (int j = 0; j < n; j++) 
        {
            if (bi[j][i] == 1)
                ctr = ctr + 1;
        }
        if (ctr >= 3
        {
  
            // If number of 1's is more than
            // 3, set flag to true and break
            flag = true;
            break;
        }
    }
  
    // if flag is true, it implies
    // that graph contains a cycle
    if (flag)
        System.out.println ("Yes");
          
    // if flag is false, no cycle
    // is there in the graph
    else
        System.out.println("No");
}
  
// Driver code
public static void main (String[] args)
{
    int ar[] = { 26, 33, 35, 40, 50 };
    int n = ar.length;
    checkCycle(ar, n);
}
}
  
// The code is contrubted by ajit

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of
# the above approach
  
# Maximum numner of bits in Arr[i]
MAX = 64
  
# Function to check if a cycle
# exists in the given graph
def checkCycle(ar, n):
    bi = [[0 for i in range(MAX)] 
             for j in range(n)]
    size = -1
    flag = False
  
    # storing the given ar[i] in
    # binary in the array
    # where bi[i] is the
    # binary value of ar[i]
    for i in range(n):
        size = 0
        while ar[i]:
            bi[i][size] = ar[i] % 2
            ar[i] //= 2
            size += 1
  
    # Checking if any column
    # contains at least 3 1's
    for i in range(MAX):
        ctr = 0
        for j in range(n):
            if bi[j][i] == 1:
                ctr += 1
  
        if ctr >= 3:
  
            # If number of 1's is more than
            # 3, set flag to true and break
            flag = True
            break
  
    # if flag is true, it implies
    # that graph contains a cycle
    if flag:
        print("Yes")
  
    # if flag is false, no cycle
    # is there in the graph
    else:
        print("No")
  
# Driver Code
if __name__ == "__main__":
    ar = [26, 33, 35, 40, 50]
    n = len(ar)
    checkCycle(ar, n)
      
# This code is contributed by
# sanjeev2552

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of
// the above approach
using System;
  
class GFG 
{
      
// Maximum numner of bits in Arr[i]
static int MAX = 64;
  
// Function to check if a cycle
// exists in the given graph
static void checkCycle(int []ar, int n)
{
    int [,]bi = new int[n, MAX];
    int size;
    Boolean flag = false;
  
    // storing the given ar[i] in
    // binary in the array
    // where bi[i] is the
    // binary value of ar[i]
    for (int i = 0; i < n; i++) 
    {
        size = 0;
        while (ar[i] != 0) 
        {
            bi[i, size++] = ar[i] % 2;
            ar[i] = ar[i] / 2;
        }
    }
  
    // Checking if any column
    // contains at least 3 1's
    for (int i = 0; i < MAX; i++)
    {
        int ctr = 0;
        for (int j = 0; j < n; j++) 
        {
            if (bi[j, i] == 1)
                ctr = ctr + 1;
        }
        if (ctr >= 3) 
        {
  
            // If number of 1's is more than
            // 3, set flag to true and break
            flag = true;
            break;
        }
    }
  
    // if flag is true, it implies
    // that graph contains a cycle
    if (flag)
        Console.WriteLine("Yes");
          
    // if flag is false, no cycle
    // is there in the graph
    else
        Console.WriteLine("No");
}
  
// Driver code
public static void Main (String[] args)
{
    int []ar = { 26, 33, 35, 40, 50 };
    int n = ar.Length;
    checkCycle(ar, n);
}
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

Yes


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.