Maximize XOR by selecting 3 numbers in range [0, A], [0, B], and [0, C] respectively
Given 3 integers A, B, C, the task is to find the maximum XOR value of three number selected one from each range [0, A], [0, B], [0, C] respectively.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: A = 1, B = 2, C = 4
Explanation: Maximum XOR can be calculated by selecting 1 (from [0, 1]), 2 (from [0, 2]) & 4 (from [0, 4]) i.e. 1⊕ 2⊕ 4 = 7
Input: A = 6, B = 2, C = 10
Explanation: Maximum XOR can be calculated by selecting 5 (from [0, 6]), 1 (from [0, 2]) & 10 (from [0, 10]) i.e. 5⊕ 1⊕ 10 = 15.
Naive Approach: Generate all possible triplets in the above ranges and calculate the maximum XOR possible.
Time Complexity: O(A*B*C)
Auxiliary Space: O(1)
To find the largest value of an XOR operation, the value of XOR should have every bit to be a set bit i.e In a 32-bit number, the goal is to get the most 1 set starting left to right. This can be done by following the below steps:
- Create a variable ans which will store the value of maximum xor possible and initialize it to zero.
- To create a 32-bit value that would be maximum xor possible, run a loop for each of its bits from most significant bit to least significant bit.
- Now for each bit:
- Create a variable cur that will store the minimum number in which that bit is set.
- Check each range A, B, C and try to find a number which has a set bit on that position. This can be done by comparing A, B & C with cur, i.e. if any number from A, B & C is greater than or equal to cur then it will contain a set bit in that position. If a set bit is found in any of the number from A, B, C then maximum xor will also contain set bit at that position.
- Now, if a set bit is found, then add cur to ans to set that bit in it, and decrease the value of the number in which the set bit is found (from A, B, C) by cur to unset that bit as it cannot be used again.
- Do the above steps for each bit, to calculate the final value of answer.
- After the above steps, print the required result.
Time Complexity: O(1)
Auxiliary Space: O(1)