# Find last element in Array formed from bitwise AND of array elements

• Last Updated : 29 Sep, 2022

Given an array A[] of size N, the task is to find the last remaining element in a new array B containing all pairwise bitwise AND of elements from A i.e., B consists of Nâ‹…(N âˆ’ 1) / 2 elements, each of the form Ai & Aj for some 1 â‰¤ i < j â‰¤ N. And we can perform the following operation any number of times on a new array till there is only one element remaining such as:

• Let X and Y be the current maximum and minimum elements of array B respectively and remove X and Y from array B and insert X|Y into it.

Examples:

Input: A[] = {2, 7, 1}
Output: 3
â€¨Explanation: Array B will be [A1 & A2, A1 & A3, A2 & A3] = [2 & 7, 2 & 1, 7 & 1] = [2, 0, 1].
Then, we do the following operations on B:
Remove 2 and 0 from B and insert 2|0=2 into it. Now, B=[1, 2].
Remove 2 and 1 from B and insert 2|1=3 into it. Now, B=[3].
The last remaining element is thus 3.

Input: A[] = {4, 6, 7, 2}
Output: 6

Approach: The problem can be solved based on the following observation:

Observations:

• The property of bitwise or is that if we are performing X | Y, bit i will be set if atleast one of bit i in X or Y is set.
• This leads us to the most crucial observation of the problem, for every bit i, if bit i is set in atleast one of B1, B2, â€¦BNâ‹…(Nâˆ’1)/2, then bit i will be set in the final remaining element of B when all the operations are performed. We donâ€™t need to worry about how the operations are performed.
• For bit i to be set in atleast one element of B, we need to have atleast 2 elements in A say j and k where Aj and Ak both have bit i set. This sets the bit i in Aj & Ak.
• Now we have the following solution, iterate over every valid bit i, count the number of elements in array A which have bit i set. If this count is greater than 1, the final answer will have bit i set else it will be unset.

Follow the steps mentioned below to implement the idea:

• Create an array of size 32 to store the count of bits set in ith position.
• Traverse the array and for each array element:
• Find the positions in which the bit is set.
• Increment the set bit count for that position by 1.
• Traverse the array storing the set bit count.
• If the count is at least 2, set that bit in the final answer.
• Return the number formed as the required answer.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the approach` `#include ` `using` `namespace` `std;`   `// Function to find last remaining` `// element in a new array` `int` `find(``int` `a[], ``int` `n)` `{` `    ``int` `count = 0;` `    ``int` `b[33] = { 0 };` `    ``for` `(``int` `bit = 30; bit >= 0; bit--) {` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``if` `(((1 << bit) & (a[i])) != 0) {` `                ``b[bit]++;` `            ``}` `        ``}` `    ``}` `    ``for` `(``int` `bit = 30; bit >= 0; bit--) {` `        ``if` `(b[bit] > 1)` `            ``count = count + (1 << bit);` `    ``}` `    ``return` `count;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `A[] = { 2, 7, 1 };` `    ``int` `N = 3;`   `    ``// Function call` `    ``cout << (find(A, N));` `    ``return` `0;` `}`   `// This code is contributed by Rohit Pradhan`

## Java

 `// Java code to implement the approach`   `import` `java.io.*;` `import` `java.util.*;`   `public` `class` `GFG {`   `    ``// Function to find last remaining` `    ``// element in a new array` `    ``public` `static` `int` `find(``int` `a[], ``int` `n)` `    ``{` `        ``int` `count = ``0``;` `        ``int` `b[] = ``new` `int``[``33``];` `        ``for` `(``int` `bit = ``30``; bit >= ``0``; bit--) {` `            ``for` `(``int` `i = ``0``; i < n; i++) {` `                ``if` `(((``1` `<< bit) & (a[i])) != ``0``) {` `                    ``b[bit]++;` `                ``}` `            ``}` `        ``}` `        ``for` `(``int` `bit = ``30``; bit >= ``0``; bit--) {` `            ``if` `(b[bit] > ``1``)` `                ``count = count + (``1` `<< bit);` `        ``}` `        ``return` `count;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `A[] = { ``2``, ``7``, ``1` `};` `        ``int` `N = A.length;`   `        ``// Function call` `        ``System.out.println(find(A, N));` `    ``}` `}`

## Python3

 `# Python code for the above approach`   `# Function to find last remaining element in a new array` `def` `find(a, n):` `    ``count ``=` `0` `    ``b ``=` `[``0``] ``*` `33` `    ``for` `bit ``in` `range``(``30``, ``-``1``, ``-``1``):` `        ``for` `i ``in` `range``(n):` `            ``if``(((``1` `<< bit) & (a[i])) ``is` `not` `0``):` `                ``b[bit] ``+``=` `1`   `    ``for` `bit ``in` `range``(``30``, ``-``1``, ``-``1``):` `        ``if``(b[bit] > ``1``):` `            ``count ``=` `count ``+` `(``1` `<< bit)`   `    ``return` `count`   `A ``=` `[``2``, ``7``, ``1``]` `N ``=` `len``(A)`   `# Function call` `print``(find(A, N))`   `# This code is contributed by lokesh`

## C#

 `// C# implementation of the approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{` `    ``// Function to find last remaining` `    ``// element in a new array` `    ``public` `static` `int` `find(``int``[] a, ``int` `n)` `    ``{` `        ``int` `count = 0;` `        ``int``[] b = ``new` `int``[33];` `        ``for` `(``int` `bit = 30; bit >= 0; bit--) {` `            ``for` `(``int` `i = 0; i < n; i++) {` `                ``if` `(((1 << bit) & (a[i])) != 0) {` `                    ``b[bit]++;` `                ``}` `            ``}` `        ``}` `        ``for` `(``int` `bit = 30; bit >= 0; bit--) {` `            ``if` `(b[bit] > 1)` `                ``count = count + (1 << bit);` `        ``}` `        ``return` `count;` `    ``}`   ` ``// Driver code` ` ``public` `static` `void` `Main(String[] args)` ` ``{` `     ``int``[] A = { 2, 7, 1 };` `        ``int` `N = A.Length;`   `        ``// Function call` `       ``Console.WriteLine(find(A, N));` ` ``}` `}`   `// This code is contributed by code_hunt.`

## Javascript

 ``

Output

`3`

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

My Personal Notes arrow_drop_up
Related Articles