Open In App

Bitwise AND of all unordered pairs from a given array

Improve
Improve
Like Article
Like
Save
Share
Report

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:
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++




// 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




// 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




# 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#




// 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


Javascript




<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>


Output: 

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]) 
 

(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++




// 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




// 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


Python3




# 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#




// 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


Javascript




<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>


Output: 

4

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Last Updated : 26 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads