VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-last-element-in-array-formed-from-bitwise-and-of-array-elements/

⇱ Find last element in Array formed from bitwise AND of array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


Output
3

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

Comment
Article Tags: