VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-bitwise-or-operations-to-make-any-two-array-elements-equal/

⇱ Minimum Bitwise OR operations to make any two array elements equal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Bitwise OR operations to make any two array elements equal

Last Updated : 18 Nov, 2021

Given an array arr[] of integers and an integer K, we can perform the Bitwise OR 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: arr[] = {1, 9, 4, 3}, K = 3 
Output:
We can OR a[0] with x, which makes it 3 which is equal to a[3]
Input : arr[] = {13, 26, 21, 15}, K = 13 
Output : -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. 
 


 

  • The answer will be 0, if there are already equal elements in the array.
  • For the answer to be 1, we will create a new array b[] which holds b[i] = (a[i] | K)
    Now, for each a[i] we will check if there is any index j such that i != j and a[i] = b[j]
    If yes, then the answer will be 1.
  • For the answer to be 2, we will check for an index i in the new array b[]
    if there is any index j such that i != j and b[i] = b[j]
    If yes, then the answer will be 2.
  • If any of the above conditions is not satisfied then the answer will be -1.


Below is the implementation of the above approach: 
 


Output: 
1

 

Time Complexity: O(n)

Auxiliary Space: O(n)

Comment