# Bitwise AND of all unordered pairs from a given array

• Difficulty Level : Easy
• Last Updated : 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:

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.

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 ``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);``    ``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

 ``
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 & arr) & (arr & arr) & (arr & arr) & (arr & arr) & (arr & arr) & (arr & arr)

(arr & arr & arr) & (arr & arr & arr) & (arr & arr & arr) & (arr & arr & arr)

• 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 & arr & arr & arr, 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 ``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);``    ``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

 ``
Output:
`4`

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

My Personal Notes arrow_drop_up