aloalgo.com

Bit Manipulation: The Binary Tricks

Bit manipulation can feel like magic - a few XORs here, some shifts there, and suddenly you've solved a problem in O(1) space that would otherwise require O(n). While not every interview includes bit manipulation, knowing these techniques gives you elegant solutions to certain problems and demonstrates low-level thinking that impresses interviewers.
Binary Basics
Before diving into tricks, let's review the fundamental bitwise operators.
Essential Bit Tricks
Check if Number is Even or Odd
Check if Power of Two
Get, Set, Clear, and Toggle Bits
Remove Rightmost Set Bit
Isolate Rightmost Set Bit
Pattern 1: Count Set Bits (Hamming Weight)
Count the number of 1 bits in a number. This is a classic interview question with multiple solutions.
Count Bits for Range [0, n]
Pattern 2: XOR Magic
XOR has special properties that make it incredibly useful:
  • a ^ a = 0 (number XOR itself is 0)
  • a ^ 0 = a (number XOR 0 is itself)
  • a ^ b ^ a = b (XOR is reversible)
  • XOR is commutative and associative
Find Single Number
Find Missing Number
Find Two Single Numbers
Swap Without Temp Variable
Pattern 3: Bit Masking
Bit masks use binary numbers to represent sets or flags efficiently. Each bit position represents whether an element is included.
Generate All Subsets
Subset Sum with Bitmask DP
Pattern 4: Bitwise Operations on Characters
ASCII characters have useful bit patterns that enable clever tricks.
Pattern 5: Reverse and Rotate Bits
Pattern 6: Binary Addition
Pattern 7: Hamming Distance
Complexity Summary
Quick Reference: Common Bit Formulas
Common Mistakes to Avoid
  1. Operator precedence: Bitwise operators have lower precedence than comparison. Use parentheses: (n & 1) == 0, not n & 1 == 0.
  2. Signed vs unsigned: Python integers have arbitrary precision. Use masks (like 0xFFFFFFFF) when you need fixed-width behavior.
  3. Shifting negative numbers: Right-shifting negative numbers is arithmetic (preserves sign) in Python, which may not be what you expect.
  4. Off-by-one in bit positions: Remember bit positions are 0-indexed from the right.
Practice Problems
Try these problems to solidify your understanding:Easy:Medium:
Was this helpful?
© 2026 aloalgo.com. All rights reserved.