#2429
Minimize XOR
MediumGreedyBit ManipulationBit ManipulationGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal approach leverages bit manipulation to construct the integer x directly. By focusing on the bits of num1 and num2, we can efficiently find the integer x that minimizes the XOR without generating all possibilities.
⚙️
Algorithm
6 steps- 1Step 1: Count the number of set bits in num2.
- 2Step 2: Initialize x to 0 and a variable to track remaining set bits.
- 3Step 3: Iterate through the bits of num1 from the most significant to the least significant bit.
- 4Step 4: If the current bit in num1 is 0 and we still have set bits left, set that bit in x to 1.
- 5Step 5: If the current bit in num1 is 1, set that bit in x to 1 if we still have set bits left, otherwise leave it as 0.
- 6Step 6: If there are still set bits left after processing num1, fill the least significant bits of x with 1s.
solution.py19 lines
1# Full working Python code
2class Solution:
3 def minXor(self, num1: int, num2: int) -> int:
4 set_bits = bin(num2).count('1')
5 x = 0
6 remaining_bits = set_bits
7 for i in range(31, -1, -1): # Check bits from 31 to 0
8 if (num1 & (1 << i)) == 0 and remaining_bits > 0:
9 x |= (1 << i) # Set this bit in x
10 remaining_bits -= 1
11 elif (num1 & (1 << i)) != 0 and remaining_bits > 0:
12 x |= (1 << i) # Set this bit in x
13 remaining_bits -= 1
14 # Fill remaining bits with 1s from the least significant side
15 for i in range(0, 32):
16 if remaining_bits > 0:
17 x |= (1 << i)
18 remaining_bits -= 1
19 return xℹ
Complexity note: This complexity is constant because we are only iterating through a fixed number of bits (32 bits for integers).
- 1Understanding how XOR works can help in minimizing the result by manipulating bits effectively.
- 2The number of set bits in the target number (num2) is crucial in constructing the optimal solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.