![]() |
VOOZH | about |
Given an array of integers of size 'n' and an integer 'k',
We can perform the Bitwise AND operation between any array element and 'k' any number of times.
The task is to print the minimum number of such operations required to make any two elements of the array equal.
If it is not possible to make any two elements of the array equal after performing the above mentioned operation then print '-1'.
Examples:
Input : k = 6 ; Array : 1, 2, 1, 2
Output : 0
Explanation : There are already two equal elements in the array so the answer is 0.
Input : k = 2 ; Array : 5, 6, 2, 4
Output : 1
Explanation : If we apply AND operation on element '6', it will become 6&2 = 2
And the array will become 5 2 2 4,
Now, the array has two equal elements, so the answer is 1.
Input : k = 15 ; Array : 1, 2, 3
Output : -1
Explanation : No matter how many times we perform the above mentioned operation,
this array will never have equal element pair. So the answer is -1
Approach:
The key observation is that if it is possible to make the desired array then the answer will be either '0', '1', or '2'. It will never exceed '2'.
Because, if (x&k) = y
then, no matter how many times you perform (y&k)
it'll always give 'y' as the result.
Below is the implementation of the above approach:
1
Time Complexity: O(n)
Auxiliary space: O(n) it is using extra space for unordere_map and array b