Bit Manipulation
Use AND, OR, XOR and shifts for compact, fast tricks.
- visited / done
- active this step
- result
- ruled out
Start at 0
XOR with 0 changes nothing, so 0 is a safe starting value.
VARIABLES
- x
- -
- result
- 0 (000)
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Integers are stored as bits. Operators like & (and), | (or), ^ (xor), << and >> (shifts) read and change those bits directly.
Why it matters
Some problems have neat O(1)-space answers with bits: finding the odd one out, counting set bits, or treating a subset as a bitmask.
Think of it like this
A row of light switches: each bit is one switch, and a mask flips or checks several at once.
Use it when
- Every number appears twice except one (XOR)
- Counting or checking set bits
- Subsets of a small set as bitmasks (n ≤ 20)
Avoid it when
- Readability matters more than a tiny speed-up
- Negative numbers in Python when 32-bit behaviour is expected - mask with 0xFFFFFFFF
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| XOR all the numbers | O(n) | O(1) |
| Count set bits with x & (x − 1) | O(set bits) | O(1) |
| Try every mask of n bits | O(2ⁿ) | O(1) |
Often confused with: hash sets - they also find the unique number, but use O(n) memory.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- x & (x − 1) clears the lowest set bit
- x ^ x = 0 and x ^ 0 = x
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Expecting ~x to flip bits unsigned - in Python ~x is −x − 1
- Forgetting Python ints never overflow, so negatives don’t wrap at 32 bits
- Using bit tricks where they hurt clarity
Edge cases to test
- A single-element array
- Negative numbers
- Zero in the input
Knowledge check
Quick check to lock in the intuition.
What does x & (x − 1) do?
Practice
Apply what you just watched on real interview problems.