Bit Manipulation
Signal: "without extra space", "every element appears twice except one", counting set bits, powers of two, subsets as masks, or toggling flags.
Core idea: integers are bit vectors, and bitwise operators process all bits at once in O(1).
| Operation | Expression | Example (x = 12 = 1100₂) | |
|---|---|---|---|
| Test bit i | (x >> i) & 1 | bit 2 → 1 | |
| Set bit i | `x \ | (1 << i)` | i=0 → 1101 |
| Clear bit i | x & ~(1 << i) | i=3 → 0100 | |
| Clear lowest set bit | x & (x − 1) | 1000 | |
| Isolate lowest set bit | x & −x | 0100 | |
| Power of two? | x > 0 and x & (x − 1) == 0 | false |
XOR superpowers
a ^ a = 0, a ^ 0 = a, and XOR is commutative and associative. So XOR-ing a list where every value appears twice except one cancels the pairs and leaves the single value.
python
def single(nums):
r = 0
for x in nums:
r ^= x
return rLanguage quirks
Python integers are arbitrary precision (there's no 32-bit overflow, and ~x == −x − 1). JavaScript bitwise operators work on 32-bit signed integers, so use >>> 0 to treat a result as unsigned.