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 - Greedy Bit Manipulation INPUT num1 = 3 (decimal) 0 0 1 1 = 0011 num2 = 5 (decimal) 0 1 0 1 = 0101 Set bits in num2: 2 bits (positions 0, 2) GOAL: Find x with 2 set bits that minimizes x XOR num1 ALGORITHM STEPS 1 Count set bits num2 has 2 set bits 2 Match MSB first Copy set bits from num1 starting from highest 3 Fill remaining If need more bits, add from LSB positions 4 Compute result x = 3, XOR = 0 (min) Calculation: x = 0011 (3) num1= 0011 (3) XOR = 0000 (0) FINAL RESULT Optimal x found: 0 0 1 1 = x OUTPUT x = 3 Verification: - Set bits in x: 2 [OK] - x XOR num1 = 0 [OK] - Minimum possible [OK] Key Insight: To minimize XOR, match as many high-order bits as possible with num1. Each matching bit produces 0 in XOR result. If x needs more set bits than num1 has, fill from lowest positions to minimize the added value. Greedy from MSB ensures optimal result. TutorialsPoint - Minimize XOR | Greedy Bit Manipulation Approach
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