#476
Number Complement
EasyBit ManipulationBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal approach leverages bit manipulation to find the complement without converting to binary strings. This is efficient and operates directly on the integer's bits.
⚙️
Algorithm
2 steps- 1Step 1: Create a mask with all bits set to 1 that are relevant to the number.
- 2Step 2: XOR the number with the mask to flip the bits.
solution.py5 lines
1# Full working Python code
2
3def findComplement(num):
4 mask = (1 << num.bit_length()) - 1
5 return num ^ maskℹ
Complexity note: The time complexity is O(1) since we perform a constant number of operations regardless of the input size. The space complexity is also O(1) as we only use a few variables.
- 1Understanding bit manipulation can lead to more efficient solutions.
- 2Using XOR is a powerful technique for flipping bits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.