Find a pair of numbers with set bit count as at most that of N and whose Bitwise XOR is N
Given a positive integer N, the task is to find the pair of integers (X, Y) such that the Bitwise XOR of X and Y is N and X * Y is maximum where the count of bits in X and Y is less than or equal to N.
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: N = 10
Output: 13 7
Explanation: The case where X = 13 and Y = 7 is the most optimal choice as 13 xor 7 = 10 and 13 * 7 = 91 which is maximum possible.
Input: N = 45
Output: 50 31
Approach: The given problem can be solved using the following observations:
- If the ith bit of N is 0, then the ith bit of both X and Y must be either 0 or 1. In order to maximize the product, set such bits as 1.
- If the ith bit of N is 1, then one of the ith bits of X or Y must be 1 and the other must be 0. Since N must have a constant number of set bits, therefore the sum of X and Y must be constant.
- If the sum of two numbers is constant, their product is maximum when the difference between the two numbers is minimized.
According to the above observations, initialize two integers X and Y as 0. In order to minimize the difference between X and Y, X must be equal to the MSBN and Y must be equal to N – MSBN where MSB represents the Most Significant Bit. Also, for all the 0 bits in N, set the respective bits in both X and Y as 1.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(N)