Learn the pattern · ~15 min
Bit Tricks & Bitmasking
also called bitwise operations, XOR tricks
Treat a number as a row of independent on/off bits. XOR flips them, so anything that appears twice cancels itself, and only the odd one out survives, in O(n) time and O(1) space.
Reach for it when you read
- +"Every element appears twice (or k times) except one", with O(1) extra space.
- +Count, test, set or clear individual bits: number of 1 bits, power of two, reverse bits.
- +A set of up to about 20–26 things (letters, items) that you compare or combine: store it as a mask and use one
&. - +Parity questions: "each letter an even number of times" becomes an XOR of prefix masks.
- +Add or compare numbers without
+: carry =(a & b) << 1, sum without carry =a ^ b.
Not this one when
- ×Counting occurrences of values when nothing cancels in pairs: a hash map.
- ×Choosing subsets of more than about 25 items: a mask can't list them all; look for DP or meet in the middle.
- ×Huge numbers mod a prime, primes, gcd: that's math (sieve, fast power), not bit tricks.
Learn Bit Tricks & Bitmasking
First, what is a bit?
A computer stores an integer in binary: a row of 0s and 1s, each one a bit. Bit 0 is the rightmost one and is worth 1, bit 1 is worth 2, bit 2 is worth 4, and so on, doubling each time.
Take 44. It's 32 + 8 + 4, so bits 5, 3 and 2 are on:
| bit | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|
| worth | 32 | 16 | 8 | 4 | 2 | 1 |
| 44 | 1 | 0 | 1 | 1 | 0 | 0 |
So 44 is 101100. An int has 32 bits, and bit manipulation works on all of them at once.
Three operators work per column. With 12 = 1100 and 10 = 1010:
&(AND) keeps a 1 where both have one:12 & 10 = 1000= 8.|(OR) keeps a 1 where either has one:12 | 10 = 1110= 14.^(XOR) keeps a 1 where they differ:12 ^ 10 = 0110= 6.
x << 1 shifts every bit one place left (doubles x); x >> 1 shifts right (halves it, rounding down).
The basic moves on one number
Every bit trick is built from these moves, here on x = 44 = 101100. 1 << b is a number with only bit b on.
| move | code | what happens | result |
|---|---|---|---|
| is bit 2 on? | (x >> 2) & 1 |
slide bit 2 down to position 0, keep only it | 1 |
| turn bit 0 on | x | (1 << 0) |
OR with 000001: bit 0 becomes 1 |
45 = 101101 |
| turn bit 3 off | x & ~(1 << 3) |
~ flips 001000 into 110111; AND keeps everything but bit 3 |
36 = 100100 |
| flip bit 5 | x ^ (1 << 5) |
XOR with 100000: that one bit swaps |
12 = 001100 |
| double, halve | x << 1, x >> 1 |
the row moves one place | 88, 22 |
| clear the lowest 1 | x & (x - 1) |
the lowest 1 is bit 2, and it goes | 40 = 101000 |
| keep only the lowest 1 | x & -x |
everything except bit 2 goes | 4 = 000100 |
| count the 1s | repeat x &= x - 1 |
44 → 40 → 32 → 0, three rounds | 3 |
The code for it
bool hasBit(int x, int b) { return (x >> b) & 1; } // slide bit b down, keep it
int setBit(int x, int b) { return x | (1 << b); }
int clearBit(int x, int b) { return x & ~(1 << b); }
int toggleBit(int x, int b) { return x ^ (1 << b); }
int dropLow(int x) { return x & (x - 1); } // clears the lowest 1
unsigned lowBit(unsigned x) { return x & -x; } // keeps only the lowest 1
int countOnes(unsigned x) {
int count = 0;
while (x != 0) { x &= x - 1; count++; } // one round per 1 bit
return count;
}You don't need to memorise this. Each line is a row of the table: shift and AND to read, OR to switch on, AND with the flipped mask to switch off, XOR to flip.
The one line that looks like magic is x & (x - 1). Why does it clear the lowest 1? Look at what subtracting 1 does to 44:
x = 101100
x - 1 = 101011Subtracting 1 borrows from the lowest 1: that bit becomes 0 and every 0 below it becomes 1. Everything above it is untouched. AND the two, and the changed stretch becomes all zeros while the top stays. x & -x works the same way, because -x is ~x + 1 (here 010100): the only 1 it shares with x is the lowest one.
Fine, but how does this help us?
Here's a classic problem: Single Number. Every value in the array appears exactly twice, except one, which appears once. Find it in one pass with O(1) extra memory.
For [5, 3, 6, 3, 5], by hand:
| value | how often it appears | single? |
|---|---|---|
| 5 | at index 0 and 4 | no |
| 3 | at index 1 and 3 | no |
| 6 | only at index 2 | yes |
The answer is 6.
The brute force
As by hand: for each value, count how often it appears.
int bruteSingle(const vector<int>& nums) {
for (int v : nums) {
int seen = 0;
for (int w : nums) if (w == v) seen++;
if (seen == 1) return v;
}
return -1;
}It's correct and needs no extra memory, but it's n² comparisons: 9 × 10⁸ at LeetCode's limit of n = 3 × 10⁴. A loop this plain is fast enough in C++ to pass, but the problem asks for linear time, and at n = 10⁶ it's 10¹². A hash map of counts is O(n) but stores up to n / 2 + 1 entries; you're allowed one number.
The one thought that fixes it
Forget the values; count the 1s in each bit column:
| column | 5 = 101 |
3 = 011 |
6 = 110 |
3 = 011 |
5 = 101 |
count of 1s |
|---|---|---|---|---|---|---|
| bit 2 | 1 | 0 | 1 | 0 | 1 | 3, odd |
| bit 1 | 0 | 1 | 1 | 1 | 0 | 3, odd |
| bit 0 | 1 | 1 | 0 | 1 | 1 | 4, even |
Each pair adds 0 or 2 to a column. Only the single value can make a column odd. The odd columns are bits 2 and 1: 110 = 6. That's our answer.
And "is this column's count odd?" is exactly what XOR computes: XOR all the values and every column comes out as its parity. Since a ^ a = 0, a ^ 0 = a and XOR can be done in any order, the pairs don't need to be next to each other.
The code for the problem
int singleNumber(const vector<int>& nums) {
int x = 0;
for (int v : nums) x ^= v; // each column keeps its parity
return x;
}Dry run
Same array, [5, 3, 6, 3, 5]. Watch x.
| v | v in binary | what happens | x after |
|---|---|---|---|
| 5 | 101 |
0 ^ 5 | 101 = 5 |
| 3 | 011 |
bits 2 and 1 differ, bit 0 cancels | 110 = 6 |
| 6 | 110 |
6 ^ 6 cancels everything | 000 = 0 |
| 3 | 011 |
0 ^ 3 | 011 = 3 |
| 5 | 101 |
bits 2 and 1 differ, bit 0 cancels | 110 = 6 |
x hits 0 halfway (6 = 5 ^ 3) and ends at 6, the same answer as the brute force.
Why it's O(n)
Each value is XORed once, and one XOR handles all 32 columns: O(n) time. The only memory is x: O(1) space.
From O(n²) down to O(n) and one variable, by counting columns instead of values.
Every other value appears three times? Count each column mod 3
XOR can't cancel triples. Count the 1s in each column yourself and keep the columns whose count isn't a multiple of 3:
for (int k = 0; k < 32; k++) {
int c = 0;
for (int v : nums) c += (v >> k) & 1;
if (c % 3) r |= 1u << k; // this column belongs to the single
}For [2, 7, 2, 2]: column 0 has 1 one, column 1 has 4, column 2 has 1. None is a multiple of 3, so all three bits are on: 7.
Two singles? Split by one bit they differ in
XOR everything and you get a ^ b. Since a ≠ b, it has at least one 1: a bit where they differ. Take its lowest 1 with x & -x and split all values into "that bit on" and "that bit off". Each group holds one single plus whole pairs, so XOR each group.
For [1, 2, 1, 3, 2, 5]: everything XORs to 6 = 110, lowest 1 is the value 2. On: 2, 3, 2 → 3. Off: 1, 1, 5 → 5.
Count the 1s of every number 0..n
i & (i − 1) is i without its lowest 1, a smaller number you've already solved. So dp[i] = dp[i & (i − 1)] + 1. For n = 5: [0, 1, 1, 2, 1, 2].
Power of two?
A power of two has exactly one 1, so clearing it leaves 0: x > 0 && (x & (x - 1)) == 0. 16 is; 12 isn't (12 & 11 = 8).
Remember this
- Pairs cancel under XOR. "Appears twice except one" in O(1) space is a XOR question.
x & (x − 1)clears the lowest 1;x & -xkeeps only it.==binds tighter than&: write(x & 1) == 0, notx & 1 == 0.1 << 31is already the sign bit of anint, and-xoverflows atINT_MIN: use1u,1LLorunsigned.
Practise it on Single Number, then Number of 1 Bits (clear the lowest 1), Counting Bits (the dp above), Single Number II (count mod 3), Single Number III (split by one bit) and Bitwise AND of Numbers Range.
Watch it work, line by line
Single Number ↗, nums = [2, 1, 4, 1, 2] → 4. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Can I treat each number as independent bits, or a small set as a mask, where doing the same thing twice undoes it?
Reach for it when
- +'every element appears twice except'
- +count set bits / power of two
- +operations on subsets as integers
- +per-bit independence of XOR/AND/OR
- +values < 231 or 263
It fails when
- ×Large/continuous values where you need ranking or sumsuse Arrays or heaps
- ×Set too big for a mask (>64 items to store, >~20 to enumerate 2ⁿ)use A real set
- ×It looks numeric but needs ordering or searchuse Binary search or hashing
- ×Arithmetic carries mix bits, so per-bit reasoning failsuse Ordinary arithmetic reasoning
- ×You're enumerating subset states for an optimum under small nuse Bitmask DP
Looks like it, isn't (and the other way round)
- Bitwise AND of Numbers Range looks like Simulation & Matrix Traversal, needs this pattern
Looping is O(range); the answer is the common binary prefix.
Why this pattern and not another
The structure is about bit-level identity/parity (something cancels, something is counted per bit). XOR/AND give O(1)-space, O(n)-time answers no general-purpose container matches.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What are
a ^ aanda ^ 0?Reveal0 and a. Together with "order doesn't matter", that's why pairs cancel.
2What does
x & (x − 1)do?RevealIt clears the lowest set bit. Loop it to count set bits; it's 0 exactly when x is a power of two (or 0).
3Why does XOR fail when the other numbers appear three times?Reveal
An odd count leaves the bit on. Count each bit position mod 3 instead.
Practice ladder
- 1Single Numberthe hookEasy
- 2Number of 1 Bitsclear the lowest bitEasy
- 3Counting Bitsclear the lowest bitEasy
- 4Missing Numberpairs cancelEasy
- 5Single Number IIcount each bit mod kMedium
- 6Single Number IIIsplit by one differing bitMedium
- 7Bitwise AND of Numbers Rangethe common prefix of a rangeMedium
- 8Maximum Product of Word Lengthssets as masksMedium
Finished Bit Tricks & Bitmasking? Mark it done and Lessgo moves you to the next step.