Minimum Bitwise OR operations to make any two array elements equal

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: 1 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:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// minimum operations requiredint minOperations(int a[], int n, int K){    unordered_map<int, bool> map;    for (int i = 0; i < n; i++) {         // Check if the initial array        // already contains an equal pair        if (map[a[i]])            return 0;        map[a[i]] = true;    }     // Create new array with OR operations    int b[n];    for (int i = 0; i < n; i++)        b[i] = a[i] | K;     // Clear the map    map.clear();     // Check if the solution    // is a single operation    for (int i = 0; i < n; i++) {         // If Bitwise OR operation between        // 'k' and a[i] gives        // a number other than a[i]        if (a[i] != b[i])            map[b[i]] = true;    }     // Check if any of the a[i]    // gets equal to any other element    // of the array after the operation    for (int i = 0; i < n; i++)         // Single operation        // will be enough        if (map[a[i]])            return 1;     // Clear the map    map.clear();     // Check if the solution    // is two operations    for (int i = 0; i < n; i++) {         // Check if the array 'b'        // contains duplicates        if (map[b[i]])            return 2;         map[b[i]] = true;    }     // Otherwise it is impossible to    // create such an array with    // Bitwise OR operations    return -1;} // Driver codeint main(){     int K = 3;    int a[] = { 1, 9, 4, 3 };    int n = sizeof(a) / sizeof(a[0]);     // Function call to compute the result    cout << minOperations(a, n, K);     return 0;}
// Java implementation of the approachimport java.util.HashMap; class GFG{         // Function to return the count of    // minimum operations required    public static int minOperations(int[] a, int n, int K)    {         HashMap<Integer, Boolean> map = new HashMap<>();         for (int i = 0; i < n; i++)        {             // Check if the initial array            // already contains an equal pair            if (map.containsKey(a[i]))                return 0;             map.put(a[i], true);        }         // Create new array with OR operations        int[] b = new int[n];        for (int i = 0; i < n; i++)            b[i] = a[i] | K;         // Clear the map        map.clear();         // Check if the solution        // is a single operation        for (int i = 0; i < n; i++)        {             // If Bitwise OR operation between            // 'k' and a[i] gives            // a number other than a[i]            if (a[i] != b[i])                map.put(b[i], true);        }         // Check if any of the a[i]        // gets equal to any other element        // of the array after the operation        for (int i = 0; i < n; i++)        {             // Single operation            // will be enough            if (map.containsKey(a[i]))                return 1;        }         // Clear the map        map.clear();         // Check if the solution        // is two operations        for (int i = 0; i < n; i++)        {             // Check if the array 'b'            // contains duplicates            if (map.containsKey(b[i]))                return 2;            map.put(b[i], true);        }         // Otherwise it is impossible to        // create such an array with        // Bitwise OR operations        return -1;    }     // Driver code    public static void main(String[] args)    {        int K = 3;        int[] a = { 1, 9, 4, 3 };        int n = a.length;        System.out.println(minOperations(a, n, K));    }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approach # Function to return the count of# minimum operations requireddef minOperations(a, n, K) :         map = dict.fromkeys(a,0) ;         for i in range(n) :         # Check if the initial array        # already contains an equal pair        if (map[a[i]]) :            return 0;                     map[a[i]] = True;             # Create new array with OR operations    b = [0]*n;         for i in range(n) :        b[i] = a[i] | K;     # Clear the map    map.clear();     # Check if the solution    # is a single operation    for i in range(n) :         # If Bitwise OR operation between        # 'k' and a[i] gives        # a number other than a[i]        if (a[i] != b[i]) :            map[b[i]] = True;     # Check if any of the a[i]    # gets equal to any other element    # of the array after the operation    for i in range(n) :         # Single operation        # will be enough        if a[i] not in map :            pass                 elif (map[a[i]]) :            return 1;     # Clear the map    map.clear();     # Check if the solution    # is two operations    for i in range(n) :         # Check if the array 'b'        # contains duplicates        if (map[b[i]]) :            return 2;         map[b[i]] = true;     # Otherwise it is impossible to    # create such an array with    # Bitwise OR operations    return -1;  # Driver codeif __name__ == "__main__" :     K = 3;    a = [ 1, 9, 4, 3 ];    n = len(a);     # Function call to compute the result    print(minOperations(a, n, K)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{         // Function to return the count of    // minimum operations required    public static int minOperations(int[] a,                                    int n, int K)    {         Dictionary<int,                   Boolean> map = new Dictionary<int,                                                 Boolean>();         for (int i = 0; i < n; i++)        {             // Check if the initial array            // already contains an equal pair            if (map.ContainsKey(a[i]))                return 0;             map.Add(a[i], true);        }         // Create new array with OR operations        int[] b = new int[n];        for (int i = 0; i < n; i++)            b[i] = a[i] | K;         // Clear the map        map.Clear();         // Check if the solution        // is a single operation        for (int i = 0; i < n; i++)        {             // If Bitwise OR operation between            // 'k' and a[i] gives            // a number other than a[i]            if (a[i] != b[i])                map.Add(b[i], true);        }         // Check if any of the a[i]        // gets equal to any other element        // of the array after the operation        for (int i = 0; i < n; i++)        {             // Single operation            // will be enough            if (map.ContainsKey(a[i]))                return 1;        }         // Clear the map        map.Clear();         // Check if the solution        // is two operations        for (int i = 0; i < n; i++)        {             // Check if the array 'b'            // contains duplicates            if (map.ContainsKey(b[i]))                return 2;            map.Add(b[i], true);        }         // Otherwise it is impossible to        // create such an array with        // Bitwise OR operations        return -1;    }     // Driver code    public static void Main(String[] args)    {        int K = 3;        int[] a = { 1, 9, 4, 3 };        int n = a.Length;        Console.WriteLine(minOperations(a, n, K));    }} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Function to return the count of// minimum operations requiredfunction minOperations(a, n, K) {    let map = new Map();    for (let i = 0; i < n; i++) {         // Check if the initial array        // already contains an equal pair        if (map.has(a[i]))            return 0;        map.set(a[i], true);    }     // Create new array with OR operations    let b = new Array(n);    for (let i = 0; i < n; i++)        b[i] = a[i] | K;     // Clear the map    map.clear();     // Check if the solution    // is a single operation    for (let i = 0; i < n; i++) {         // If Bitwise OR operation between        // 'k' and a[i] gives        // a number other than a[i]        if (a[i] != b[i])            map.set(b[i], true);    }     // Check if any of the a[i]    // gets equal to any other element    // of the array after the operation    for (let i = 0; i < n; i++)         // Single operation        // will be enough        if (map.has(a[i]))            return 1;     // Clear the map    map.clear();     // Check if the solution    // is two operations    for (let i = 0; i < n; i++) {         // Check if the array 'b'        // contains duplicates        if (map.has(b[i]))            return 2;         map.set(b[i], true);    }     // Otherwise it is impossible to    // create such an array with    // Bitwise OR operations    return -1;} // Driver code let K = 3;let a = [1, 9, 4, 3];let n = a.length; // Function call to compute the resultdocument.write(minOperations(a, n, K)); // This code is contributed by gfgking </script>
1
 
Time Complexity: O(n)
Auxiliary Space: O(n)
ankthon
sanjeev2552
29AjayKumar
gfgking
subhammahato348
Bit Algorithms
Bitwise-OR
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Program to find whether a given number is power of 2