Skip to content

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.

14 min read0/4 questions

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).

DecimalBinaryWhy
51014 + 1
61104 + 2
1211008 + 4
255111111118 ones = 2⁸ − 1

Both languages let you write and print binary directly:

Python
print(bin(13)) # '0b1101'print(0b1101) # 13print(format(5, "08b")) # padded to 8 bitsprint((13).bit_count()) # number of 1 bits (Python 3.10+)
Output
Press Run (⌘ Enter) to see what happens.

The operators

Each operator works on every bit position independently.

OperatorPython / JSRule per bit6 op 5 (110, 101)
ANDa & b1 if both are 1100 = 4
ORa | b1 if either is 1111 = 7
XORa ^ b1 if they differ011 = 3
NOT~aflip every bit~6 = -7
Left shifta << kmove bits left k places (× 2ᵏ)6 << 1 = 12
Right shifta >> kmove 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.

Quick check
What is 12 ^ 10?
Need a nudge? A hint rules out a wrong answer.

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 i

This 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 & (x - 1) on x = 12
8421
x1100
x - 1
x & (x-1)

x = 12 = 1100. Its lowest set bit is the 4s place.

1/4

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.

Python
def single_number(nums): result = 0 for x in nums: result ^= x # pairs cancel to 0 return result def count_ones(x): count = 0 while x: x &= x - 1 # clear the lowest set bit count += 1 return count def is_power_of_two(x): return x > 0 and x & (x - 1) == 0 print(single_number([4, 1, 2, 1, 2]))print(count_ones(12), count_ones(255))print(is_power_of_two(64), is_power_of_two(96))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

result = 0
for x in [7, 3, 5, 3, 7]:
  result ^= x
print(result)
Need a nudge? Hints walk you through it.
Quick check
In JavaScript, what does x & x - 1 === 0 evaluate to for x = 8?
Need a nudge? A hint rules out a wrong answer.

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)

Python
def count_bits(n): bits = [0] * (n + 1) for i in range(1, n + 1): bits[i] = bits[i >> 1] + (i & 1) return bits print(count_bits(8))
Output
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 bits

So 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 pairs0/5 matched

Match the goal to the expression.

Choose an item, then its match on the other side.

Common mistakes:

  • Missing parentheses in JavaScript: x & 1 === 0 means x & (1 === 0). Parenthesise bit expressions in every language.
  • Expecting 64-bit results from JavaScript bitwise operators.
  • Looping while x: with x >>= 1 on a negative Python int: it never reaches 0, because -1 >> 1 is still -1. Mask with & 0xFFFFFFFF first.
  • Using shifts as a micro-optimisation in normal code. Write * 2 unless the problem is about bits.
ChallengeEasy

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]     →  -2

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Every element appears twice except for one, which appears once.
def single_number(nums: list[int]) -> int: # XOR has a useful property: x ^ x == 0. pass
ChallengeEasy

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
def count_bits(n: int) -> list[int]: # Reuse answers you already computed for smaller numbers. pass
Key terms
bit i
The binary digit worth 2ⁱ. Test it with (x >> i) & 1.
XOR
1 where bits differ. a ^ a == 0 and a ^ 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.
Interview pattern: Bit Manipulation & Math32 problemsSpot it: "Without extra space" · single number · powers of two · digits