Lesson 30 of 40Advanced patterns
Bit Manipulation
Read numbers as bits and use AND, OR, XOR and shifts for tricks like finding the unique number in O(1) space.
Under every integer is a row of bits. Permission flags in Unix (chmod 755), feature flags packed into one database column, hash functions, compression, graphics and network masks all work directly on those bits. A handful of interview problems do too, and they share a small set of tricks that look like magic until you see the bits.
This lesson gives you the operators, the four tricks worth memorising, and the one big difference between Python and JavaScript that bites people.
Numbers in binary
In binary, each position is a power of 2, counting from the right starting at 2⁰. So 1101 is 8 + 4 + 0 + 1 = 13. Position i is called bit i; bit 0 is the rightmost (least significant).
| Decimal | Binary | Why |
|---|---|---|
| 5 | 101 | 4 + 1 |
| 6 | 110 | 4 + 2 |
| 12 | 1100 | 8 + 4 |
| 255 | 11111111 | 8 ones = 2⁸ − 1 |
Both languages let you write and print binary directly:
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The operators
Each operator works on every bit position independently.
| Operator | Python / JS | Rule per bit | 6 op 5 (110, 101) |
|---|---|---|---|
| AND | a & b | 1 if both are 1 | 100 = 4 |
| OR | a | b | 1 if either is 1 | 111 = 7 |
| XOR | a ^ b | 1 if they differ | 011 = 3 |
| NOT | ~a | flip every bit | ~6 = -7 |
| Left shift | a << k | move bits left k places (× 2ᵏ) | 6 << 1 = 12 |
| Right shift | a >> k | move bits right k places (÷ 2ᵏ, floored) | 6 >> 1 = 3 |
Why is ~6 equal to -7? Integers use two's complement, where flipping every bit of x gives -x - 1. You rarely need the details: just remember ~x == -x - 1.
12 ^ 10?Four tricks worth knowing
1. Check, set, clear and flip bit i. Build a mask with a single 1 at position i: 1 << i.
is_set = (x >> i) & 1 # 1 if bit i is on
x = x | (1 << i) # turn bit i on
x = x & ~(1 << i) # turn bit i off
x = x ^ (1 << i) # flip bit iThis is how flags are packed: READ = 1, WRITE = 2, EXEC = 4, so perms = READ | WRITE is 3, and perms & WRITE tests one permission.
2. x & (x - 1) clears the lowest set bit. Subtracting 1 flips the lowest 1 to 0 and every 0 below it to 1. AND with the original wipes all of those out.
x = 12 = 1100. Its lowest set bit is the 4s place.
Two uses fall out. Count set bits: repeat x &= x - 1 until 0 and count the steps (one step per 1 bit, not per bit position). Power of two: a power of two has exactly one 1 bit, so x > 0 and x & (x - 1) == 0.
3. XOR cancels. a ^ a == 0 and a ^ 0 == a, and order does not matter. So if you XOR a list where every number appears twice except one, the pairs cancel and the single number is left. O(n) time, O(1) space, no hash set.
4. Shifts multiply and divide by powers of two. x << 3 is x * 8; x >> 1 is x // 2. Use it when the problem is about bits (i >> 1 to drop the last bit), not as a speed trick: compilers and interpreters already optimise * 8.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.What does this print?
result = 0 for x in [7, 3, 5, 3, 7]: result ^= x print(result)
x & x - 1 === 0 evaluate to for x = 8?Counting bits for every number
Return the number of 1 bits for every number from 0 to n. Calling count_ones on each is O(n log n). There is an O(n) DP: i >> 1 is i with its last bit dropped, and you already know its answer. So:
bits[i] = bits[i >> 1] + (i & 1)
Press Run (⌘ Enter) to see what happens.Python versus JavaScript
This is the difference that causes real bugs.
Python integers are unbounded. 1 << 100 is just a big number. Negative numbers behave as if they had infinitely many 1 bits on the left, so bin(-5) prints -0b101 rather than a 32-bit pattern. If a problem expects 32-bit behaviour, mask with x & 0xFFFFFFFF.
JavaScript bitwise operators convert to 32-bit signed integers. Numbers are normally 64-bit floats, but &, |, ^, ~, << and >> first squash them to 32 bits:
console.log(1 << 31); // -2147483648: bit 31 is the sign bit
console.log(2 ** 32 | 0); // 0: bits above 31 are dropped
console.log(-1 >>> 0); // 4294967295: >>> is the unsigned right shift
console.log(1n << 100n); // BigInt for anything wider than 32 bitsSo x & (x - 1) is safe in JavaScript only while values fit in 32 bits. Use >>> when you want an unsigned result, and BigInt (1n) when you need more bits.
Match the goal to the expression.
Common mistakes:
- Missing parentheses in JavaScript:
x & 1 === 0meansx & (1 === 0). Parenthesise bit expressions in every language. - Expecting 64-bit results from JavaScript bitwise operators.
- Looping
while x:withx >>= 1on a negative Python int: it never reaches 0, because-1 >> 1is still -1. Mask with& 0xFFFFFFFFfirst. - Using shifts as a micro-optimisation in normal code. Write
* 2unless the problem is about bits.
Single Number
Every value in nums appears exactly twice, except one value that appears once. Return that value, using O(1) extra space.
nums = [2, 2, 1] → 1
nums = [4, 1, 2, 1, 2] → 4
nums = [-1, -1, -2] → -2Constraints
1 <= nums.length <= 3 * 10^4-3 * 10^4 <= nums[i] <= 3 * 10^4- Every element appears twice except for one, which appears once.
Counting Bits
Return a list ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i, for every i from 0 to n. Aim for a single O(n) pass.
n = 2 → [0, 1, 1] (0, 1, 10)
n = 5 → [0, 1, 1, 2, 1, 2] (0, 1, 10, 11, 100, 101)Constraints
0 <= n <= 10^5
- bit i
- The binary digit worth 2ⁱ. Test it with
(x >> i) & 1. - XOR
- 1 where bits differ.
a ^ a == 0anda ^ 0 == a, so pairs cancel. - x & (x - 1)
- Clears the lowest set bit. Used to count 1 bits and test powers of two.
- two's complement
- How signed integers are stored. Flipping every bit gives
~x == -x - 1. - bitmask
- An integer whose bits act as on/off flags, such as permissions or which items are in a subset.
- JS 32-bit bitwise
- JavaScript converts numbers to 32-bit signed ints for bitwise ops. Use
>>>for unsigned and BigInt for wider.