Bit Manipulation
Use bitwise operations for efficient computation. XOR tricks, counting bits, power-of-two checks, and bitmask patterns for subsets and flags.
Interactive visualization
Use the controls to connect the idea to concrete operations before diving into the full write-up.
Family
Bitwise
Compact state, masks, parity tricks, and low-level arithmetic.
Builds on
Foundational
You can start here without another page first.
Unlocks
0 next topics
Use these follow-ups when you want to apply the current idea in a richer setting.
Learning paths
1
This topic appears in curated progressions so you can keep moving without guessing the next step.
Problem
Many problems reduce to operations on individual bits. Bitwise operations execute in on fixed-width integers — a single CPU instruction. When you need to track boolean flags, enumerate subsets, or perform arithmetic tricks, bit manipulation replaces loops with constant-time expressions and compresses booleans into a single integer.
Core operations
Six operations form the basis. All operate independently on each bit position.
| Operation | Symbol | Rule |
|---|---|---|
| AND | a & b | 1 only if both bits are 1 |
| OR | a | b | 1 if either bit is 1 |
| XOR | a ^ b | 1 if bits differ |
| NOT | ~a | Flip every bit |
| Left shift | a << k | Shift bits left by , fill with 0 |
| Right shift | a >> k | Shift bits right by |
Truth table (single-bit):
| a | b | AND | OR | XOR |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Left shift by is equivalent to multiplication by . Right shift by is integer division by .
Essential tricks
Check if power of 2: A power of 2 has exactly one set bit. n & (n - 1) clears the lowest set bit — if the result is 0, is a power of 2.
is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
Isolate lowest set bit: n & (-n) extracts the lowest set bit. In two’s complement, -n = ~n + 1, so the only surviving bit is the rightmost 1.
Set bit : n | (1 << k)
Clear bit : n & ~(1 << k)
Toggle bit : n ^ (1 << k)
Check bit : (n >> k) & 1
Count set bits (Brian Kernighan): Each iteration of n = n & (n - 1) clears the lowest set bit. Count iterations until .
count_bits(n):
count ← 0
while n > 0:
n ← n & (n - 1)
count ← count + 1
return count
This runs in , not .
XOR patterns
XOR has three key properties: , , and it is commutative + associative.
Find single number: Given an array where every element appears twice except one, XOR all elements. Duplicates cancel, leaving the unique value. time, space.
Swap without temp variable: a ^= b; b ^= a; a ^= b; — works because XOR is its own inverse.
Find two unique numbers: XOR all elements to get . Find any set bit in (use x & -x). Partition elements by that bit position and XOR each group separately to recover and .
Bitmask for subsets
An integer with bits represents a subset of . Bit is set if element is in the subset.
Enumerate all subsets:
for mask in 0 to (1 << n) - 1:
for i in 0 to n - 1:
if (mask >> i) & 1:
// element i is in this subset
Enumerate subsets of a given mask (only subsets whose bits are a subset of mask):
sub ← mask
while sub > 0:
// process sub
sub ← (sub - 1) & mask
This visits every subset of mask exactly once in .
Common interview patterns
| Problem | Technique |
|---|---|
| Single Number | XOR all elements |
| Single Number II (appears 3 times) | Count bits mod 3 at each position |
| Hamming Distance | popcount(a ^ b) |
| Reverse Bits | Swap halves recursively or loop through positions |
| Missing Number (0 to ) | XOR indices with values |
| Power of Two | n & (n - 1) == 0 |
| Subsets generation | Bitmask from to |
Complexity
All single-integer bitwise operations are . Brian Kernighan’s bit count is where is the number of set bits (at most for value ). Subset enumeration with bitmask is .
Key takeaways
- XOR is the Swiss Army knife —
a ^ a = 0anda ^ 0 = asolve “find the unique element” problems in space without sorting or hash maps. n & (n - 1)clears the lowest set bit — this single trick powers power-of-two checks, Brian Kernighan’s bit counting, and many interview one-liners.- Bitmask = subset — an -bit integer naturally encodes a subset of elements, enabling enumeration and bitmask DP for NP-hard problems on small inputs.
- Bitwise operations are on fixed-width integers — replacing branching or looping with bit tricks can eliminate constant factors in hot paths.
- Isolate lowest set bit with
n & (-n)— essential for Fenwick trees (BIT) and for partitioning elements in the “two unique numbers” XOR pattern.
Practice problems
| Problem | Difficulty | Key idea |
|---|---|---|
| Single Number | 🟢 Easy | XOR all elements — duplicates cancel, leaving the unique value |
| Number of 1 Bits | 🟢 Easy | Brian Kernighan’s trick: n &= n - 1 counts set bits in |
| Counting Bits | 🟢 Easy | DP using dp[i] = dp[i & (i-1)] + 1 to count bits for every number up to |
| Reverse Bits | 🟢 Easy | Loop through 32 positions, shifting result left and extracting each bit |
| Subsets | 🟡 Medium | Use bitmask from to to enumerate all subsets |
Relation to other topics
Bit manipulation appears inside many advanced techniques. DP with bitmask uses an integer to represent visited states — common in TSP and assignment problems where tracks which elements have been used. Hash functions and bloom filters rely on bitwise mixing and bit-level addressing. XOR-based tricks show up in randomized algorithms and error detection (CRC, parity bits).
Related directions
These topics live nearby conceptually, even if they are not direct prerequisites.
Dynamic Programming
Break a problem into overlapping subproblems, solve each once, reuse the results. DP turns exponential brute force into polynomial time.
Hash Map
O(1) average-case lookups via hashing. Understand collision resolution, load factors, and when hash maps are the right (or wrong) choice.
Paths that include this topic
Follow one of these sequences if you want a guided next step instead of open-ended browsing.
Strategy playbook
A reusable set of problem-solving moves for brute-force search, greedy choices, memoized state, and advanced DP optimization.
From the blog
Pair the atlas with recent writing from the rest of the site when you want a broader engineering perspective alongside the topic graph.