Minimize XOR - Problem
Minimize XOR is a fascinating bit manipulation problem that challenges you to construct an optimal number based on XOR properties.

You're given two positive integers num1 and num2. Your task is to find a positive integer x that satisfies two critical conditions:

1. Same Set Bit Count: x must have exactly the same number of 1-bits as num2
2. Minimal XOR: The value x XOR num1 must be as small as possible

The key insight is that to minimize XOR, we want x to be as similar to num1 as possible. Since XOR returns 0 when bits are identical and 1 when they differ, we should strategically place our set bits to maximize overlap with num1's set bits.

Example: If num1 = 3 (binary: 11) and num2 = 5 (binary: 101, has 2 set bits), we need to find x with exactly 2 set bits that minimizes x XOR 3. The answer is x = 3 because 3 XOR 3 = 0, which is minimal.

Input & Output

example_1.py โ€” Basic Case
$ Input: num1 = 3, num2 = 5
โ€บ Output: 3
๐Ÿ’ก Note: num1 = 3 (011), num2 = 5 (101) has 2 set bits. We need x with 2 set bits that minimizes x โŠ• 3. Since 3 already has 2 set bits, x = 3 gives us 3 โŠ• 3 = 0, which is the minimum possible.
example_2.py โ€” Need More Bits
$ Input: num1 = 1, num2 = 12
โ€บ Output: 3
๐Ÿ’ก Note: num1 = 1 (001), num2 = 12 (1100) has 2 set bits. We start with 1, but need 2 bits total. Adding bit 1 gives us 3 (011). Result: 3 โŠ• 1 = 2.
example_3.py โ€” Need Fewer Bits
$ Input: num1 = 25, num2 = 72
โ€บ Output: 24
๐Ÿ’ก Note: num1 = 25 (11001) has 3 set bits, num2 = 72 (1001000) has 2 set bits. We start with 25 and remove the lowest set bit (bit 0), giving us 24 (11000). Result: 24 โŠ• 25 = 1.

Constraints

  • 1 โ‰ค num1, num2 โ‰ค 109
  • Both num1 and num2 are positive integers
  • The answer x is uniquely determined for each test case

Visualization

Tap to expand
๐ŸŽฏ XOR Minimization Visualizationnum1Starting Pointnum2Bit Count TargetresultOptimal xGreedy AdjustmentAlgorithm Steps1. Initializeresult = num1Count bits in bothMaximize overlap2. Calculate Needneed = |bits1 - bits2|Determine directionAdd or remove?3. Adjust OptimallyStart from bit 0Modify lowest bitsMinimize XOR impact
Understanding the Visualization
1
Start Smart
Begin with num1 to get maximum overlap
2
Count the Gap
Determine if we need more or fewer set bits
3
Adjust Minimally
Change only the lowest bits to minimize impact
Key Takeaway
๐ŸŽฏ Key Insight: Starting with num1 gives us the best possible foundation, and adjusting only the lowest necessary bits ensures we minimize the XOR difference while meeting the set bit count requirement.
Asked in
Google 15 Meta 12 Microsoft 8 Amazon 6
24.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen