Minimize operations to make X equal to Y by replacing X with its bitwise XOR with N
Given two integers X and Y, and an integer K, the task is to find the minimum number of operations to make X equal to Y by choosing a number N in range (1 ≤ N < K) and applying the XOR operation as X = X XOR N. If it is not possible, return -1.
Input: X = 7, Y = 1, K = 5
Explanation: Since in binary, X = 7 -> 111, Y = 1 -> 001,
and given that K = 5, N can be in range [1, 4].
Now there is need to change 2 bits in X to make it equal to Y.
Therefore possible values of N can be 6 (110), 4 (100), 2 (010)
- We cannot choose 6 as it is not in range [1, 4]
- We will choose 4, making X as X XOR 4 = 111 XOR 100 = 011
- Now again we will choose 2, making X as 011 XOR 010 = 001, which is same as Y.
Thus, 2 operations are needed to convert X to Y.
Input: X = 3, Y = 4, K = 10
Approach: To solve the problem follow the below observations:
Let V be the XOR of X and Y. Now, we want to get V by performing XOR of as few elements as possible, no more than N,
Decrease the value of K by 1 so that we don’t select N = K for performing XOR.
We observe the following three cases:
- if V = 0: Then we need zero operations because V=0 means X⊕Y=0 which implies X is already equal to Y.
- if V < K: Then we need only 1 operation because V < K implies it is always possible to find a number N less than equal to K
which on XOR with X will give Y.
- If log2(V) = log2(K): In 1st operation we can change the most significant bit only,
and in 2nd operation we can change all bits less than most significant one.
Hence 2 operations.
Else it is not possible to make X equal to Y by doing XOR. This happens in the case where the largest bit of V is greater than the largest bit of K, which means we cannot create this largest bit by any means. Hence we print -1.
Follow the given steps to solve the problem:
- Decrease K by 1 to avoid selecting N = K for XOR.
- Store the XOR of X and Y in a variable (say V).
- Now, find the minimum number of operations required based on the above conditions.
Below is the implementation of the above approach.
Time Complexity: O(1)
Auxiliary Space: O(1)