Bitwise AND of all unordered pairs from a given array - GeeksforGeeks

26 Jul, 2021

Given an array arr[] of size N, the task is to find the bitwise AND of all possible unordered pairs present in the given array.
Examples:
Input: arr[] = {1, 5, 3, 7}Output: 1 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7). Bitwise AND of all possible pairs = ( 1 & 5 ) & ( 1 & 3 ) & ( 1 & 7 ) & ( 5 & 3 ) & ( 5 & 7 ) & ( 3 & 7 )                                                          =  1 & 1 & 1 & 1 & 5 & 3                                                          = 1 Therefore, the required output is 1.
Input: arr[] = {4, 5, 12, 15}Output: 4
Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print Bitwise AND of each element present in these pairs of the given array. Follow the steps below to solve the problem:
Initialize a variable, say totalAND, to store Bitwise AND of each element from these pairs.
Iterate over the array and generate all possible pairs (arr[i], arr[j]) from the given array.
For each pair (arr[i], arr[j]), update the value of totalAND = (totalAND & arr[i] & arr[j]).
Finally, print the value of totalAND.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
 

 
 










// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate bitwise AND
// of all pairs from the given array
int TotalAndPair(int arr[], int N)
{
    // Stores bitwise AND
    // of all possible pairs
    int totalAND = (1 << 30) - 1;
 
    // Generate all possible pairs
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N;
             j++) {
 
            // Calculate bitwise AND
            // of each pair
            totalAND &= arr[i]
                        & arr[j];
        }
    }
    return totalAND;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 5, 12, 15 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << TotalAndPair(arr, N);
}






 

 
 










// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate bitwise AND
// of all pairs from the given array
static int TotalAndPair(int arr[], int N)
{
    // Stores bitwise AND
    // of all possible pairs
    int totalAND = (1 << 30) - 1;
 
    // Generate all possible pairs
    for (int i = 0; i < N; i++) 
    {
        for (int j = i + 1; j < N;
             j++)
        {
 
            // Calculate bitwise AND
            // of each pair
            totalAND &= arr[i]
                        & arr[j];
        }
    }
    return totalAND;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 5, 12, 15 };
    int N = arr.length;
    System.out.print(TotalAndPair(arr, N));
}
}
 
// This code is contributed by shikhasingrajput






 

 
 










# Python3 program to implement
# the above approach
 
# Function to calculate bitwise AND
# of all pairs from the given array
def TotalAndPair(arr, N):
 
  # Stores bitwise AND
  # of all possible pairs
    totalAND = (1 << 30) - 1
 
    # Generate all possible pairs
    for i in range(N):
        for j in range(i + 1, N):
 
            # Calculate bitwise AND
            # of each pair
            totalAND &= (arr[i] & arr[j])
    return totalAND
 
# Driver Code
if __name__ == '__main__':
    arr=[4, 5, 12, 15]
    N = len(arr)
    print(TotalAndPair(arr, N)) 
 
# This code is contributed by mohit kumar 29






 

 
 










// C# program to implement
// the above approach  
using System;
  
class GFG{
  
// Function to calculate bitwise AND
// of all pairs from the given array
static int TotalAndPair(int[] arr, int N)
{
     
    // Stores bitwise AND
    // of all possible pairs
    int totalAND = (1 << 30) - 1;
  
    // Generate all possible pairs
    for(int i = 0; i < N; i++) 
    {
        for(int j = i + 1; j < N; j++)
        {
             
            // Calculate bitwise AND
            // of each pair
            totalAND &= arr[i] & arr[j];
        }
    }
    return totalAND;
}
  
// Driver Code
public static void Main()
{
    int[] arr = { 4, 5, 12, 15 };
    int N = arr.Length;
     
    Console.Write(TotalAndPair(arr, N));
}
}
 
// This code is contributed by sanjoy_62






 

 
 










<script>
 
// JavaScript program to implement
// the above approach
 
// Function to calculate bitwise AND
// of all pairs from the given array
function TotalAndPair(arr, N)
{
    // Stores bitwise AND
    // of all possible pairs
    let totalAND = (1 << 30) - 1;
 
    // Generate all possible pairs
    for (let i = 0; i < N; i++) {
        for (let j = i + 1; j < N;
            j++) {
 
            // Calculate bitwise AND
            // of each pair
            totalAND &= arr[i]
                        & arr[j];
        }
    }
    return totalAND;
}
 
// Driver Code
    let arr = [ 4, 5, 12, 15 ];
    let N = arr.length;
    document.write(TotalAndPair(arr, N));
 
 
// This code is contributed by Surbhi Tyagi
 
</script>






4
 
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
Considering an array of 4 elements, required Bitwise AND is as follows:
(arr[0] & arr[1]) & (arr[0] & arr[2]) & (arr[0] & arr[3]) & (arr[1] & arr[2]) & (arr[1] & arr[3]) & (arr[2] & arr[3])  
Since Bitwise AND follows Associative property, the above expression can be rearranged as:
(arr[0] & arr[0] & arr[0]) & (arr[1] & arr[1] & arr[1]) & (arr[2] & arr[2] & arr[2]) & (arr[3] & arr[3] & arr[3])  
It can be observed that each array element occurs exactly (N – 1) times in all possible pairs.
Based on the X & X = X property of Bitwise AND operators, the above expression can be rearranged to arr[0] & arr[1] & arr[2] & arr[3], which is equal to the Bitwise AND of all elements of original array.
Follow the steps below to solve the problem: 
Initialize a variable totalAND to store the result.
Traverse the given array.
Calculate Bitwise AND of all unordered pairs by updating totalAND = totalAND & arr[i].
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
 

 
 










// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate bitwise AND
// of all pairs from the given array
int TotalAndPair(int arr[], int N)
{
    // Stores bitwise AND
    // of all possible pairs
    int totalAND = (1 << 30) - 1;
 
    // Iterate over the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Calculate bitwise AND
        // of each array element
        totalAND &= arr[i];
    }
    return totalAND;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 5, 12, 15 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << TotalAndPair(arr, N);
}






 

 
 










// Java program to implement
// the above approach
 
import java.util.*;
 
class GFG{
 
// Function to calculate bitwise AND
// of all pairs from the given array
static int TotalAndPair(int arr[], int N)
{
    // Stores bitwise AND
    // of all possible pairs
    int totalAND = (1 << 30) - 1;
 
    // Iterate over the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Calculate bitwise AND
        // of each array element
        totalAND &= arr[i];
    }
    return totalAND;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 5, 12, 15 };
    int N = arr.length;
    System.out.print(TotalAndPair(arr, N));
}
}
 
// This code is contributed by 29AjayKumar 






 

 
 










# Python program to implement
# the above approach
 
# Function to calculate bitwise AND
# of all pairs from the given array
def TotalAndPair(arr, N):
   
    # Stores bitwise AND
    # of all possible pairs
    totalAND = (1 << 30) - 1;
 
    # Iterate over the array arr
    for i in range(N):
       
        # Calculate bitwise AND
        # of each array element
        totalAND &= arr[i];
 
    return totalAND;
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 5, 12, 15];
    N = len(arr);
    print(TotalAndPair(arr, N));
     
    # This code is contributed by 29AjayKumar 






 

 
 










// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate bitwise AND
// of all pairs from the given array
static int TotalAndPair(int []arr, int N)
{
     
    // Stores bitwise AND
    // of all possible pairs
    int totalAND = (1 << 30) - 1;
     
    // Iterate over the array arr[]
    for(int i = 0; i < N; i++) 
    {
         
        // Calculate bitwise AND
        // of each array element
        totalAND &= arr[i];
    }
    return totalAND;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 4, 5, 12, 15 };
    int N = arr.Length;
     
    Console.Write(TotalAndPair(arr, N));
}
}
 
// This code is contributed by AnkThon






 

 
 










<script>
// JavaScript program to implement
// the above approach
 
// Function to calculate bitwise AND
// of all pairs from the given array
function TotalAndPair(arr, N)
{
    // Stores bitwise AND
    // of all possible pairs
    let totalAND = (1 << 30) - 1;
 
    // Iterate over the array arr[]
    for (let i = 0; i < N; i++) {
 
        // Calculate bitwise AND
        // of each array element
        totalAND &= arr[i];
    }
    return totalAND;
}
 
// Driver Code
 
    let arr = [ 4, 5, 12, 15 ];
    let N = arr.length;
    document.write(TotalAndPair(arr, N));
 
 
// This code is contributed by Surbhi Tyagi.
</script>






4
 
Time Complexity: O(N)Auxiliary Space: O(1)
 
mohit kumar 29
shikhasingrajput
sanjoy_62
29AjayKumar
ankthon
surbhityagi15
adnanirshad158

Bitwise-AND


Arrays


Bit Magic


C++ Programs


Mathematical

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?