![]() |
VOOZH | about |
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:
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:
Below is the implementation of the above approach:
3
Time Complexity: O(N)
Auxiliary Space: O(1)