Minimize XOR - Problem

Given two positive integers num1 and num2, find the positive integer x such that:

  • x has the same number of set bits as num2, and
  • The value x XOR num1 is minimal.

Note that XOR is the bitwise XOR operation.

Return the integer x. The test cases are generated such that x is uniquely determined.

The number of set bits of an integer is the number of 1's in its binary representation.

Input & Output

Example 1 — Perfect Match
$ Input: num1 = 3, num2 = 5
Output: 3
💡 Note: num1 = 3 (binary: 011) has 2 set bits. num2 = 5 (binary: 101) has 2 set bits. Since 3 already has the required number of bits, x = 3 gives XOR = 0, which is minimal.
Example 2 — Need More Bits
$ Input: num1 = 1, num2 = 12
Output: 3
💡 Note: num1 = 1 (binary: 001) has 1 set bit. num2 = 12 (binary: 1100) has 2 set bits. We need x with 2 set bits. Starting from 1, we add the lowest bit to get 3 (binary: 011). XOR: 3 ⊕ 1 = 2.
Example 3 — Need Fewer Bits
$ Input: num1 = 25, num2 = 6
Output: 17
💡 Note: num1 = 25 (binary: 11001) has 3 set bits. num2 = 6 (binary: 110) has 2 set bits. We need x with 2 set bits. Remove the highest bit from 25 to get 17 (binary: 10001) with 2 set bits.

Constraints

  • 1 ≤ num1, num2 ≤ 109
  • num1 and num2 are positive integers

Visualization

Tap to expand
Minimize XOR: Find x with same bit count as num2, minimal x⊕num1num1 = 3num2 = 5x = 3binary: 011binary: 101binary: 0112 set bits2 set bits2 set bits ✓Goal: x must have same bit count as num2 (2 bits)Minimize: x ⊕ num1 = 3 ⊕ 3 = 0Optimal solution: Use num1 directly when possible!Result: x = 3 (XOR = 0, minimal)
Understanding the Visualization
1
Input Analysis
Analyze bit patterns of num1 and num2
2
Bit Optimization
Construct x to minimize XOR
3
Result
x with required bits and minimal XOR
Key Takeaway
🎯 Key Insight: Start with num1 and greedily adjust bit count to minimize XOR while maintaining the required number of set bits
Asked in
Google 15 Microsoft 12 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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