13.1 Bit Manipulation
Understand binary numbers and bitwise operators from scratch, and master XOR pair cancellation and Brian Kernighan's n & (n - 1) lowest-bit trick.
1. What Is Bit Manipulation?
Inside hardware, every integer is stored in binary (powers of 2: ..., 8, 4, 2, 1). For example, the number 12 (8 + 4) is stored as 1100.
Bit Manipulation uses CPU-level bitwise operators (&, |, ^, ~, <<, >>) to inspect or flip those 0s and 1s directly in O(1) time and O(1) memory:
- AND (
&):1only if both bits are1. - OR (
|):1if either bit is1. - XOR (
^):1if the two bits are different,0if they are the same. - Left / Right Shift (
<<,>>):1 << iputs a1at bit positioni(2^i);(n >> i) & 1reads biti.
Truth Table & Essential Bitmask Cheat Sheet
Bit A | Bit B | A & B (AND) | A | B (OR) | A ^ B (XOR) | Everyday Rule to Remember |
|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | x & 0 = 0 (AND with 0 clears a bit) |
0 | 1 | 0 | 1 | 1 | x | 1 = 1 (OR with 1 turns ON a bit) |
1 | 0 | 0 | 1 | 1 | x ^ 0 = x (XOR with 0 keeps x unchanged) |
1 | 1 | 1 | 1 | 0 | x ^ x = 0 (XOR with itself cancels to 0!) |
- Check if
nis a Power of Two (1, 2, 4, 8, 16...): Powers of two have exactly one1-bit in binary (8 = 1000). Son > 0 and (n & (n - 1)) == 0isTrueif and only ifnis a power of two! - Isolate the Lowest Set
1-Bit (n & -n): In two's complement binary,-nis~n + 1, son & -nkeeps only the rightmost1-bit (used in Fenwick / Binary Indexed Trees).
2. Why Do We Need Bit Manipulation & How Do the Two Core Tricks Work?
Trick 1: XOR Pair Cancellation (x ^ x = 0 and x ^ 0 = x)
Suppose an array has 99,999 numbers where every number appears twice except one unique number (Single Number), or a range 0..N is missing one number (Missing Number).
- A Hash Set finds the answer in
O(N)time, but usesO(N)extra memory. - Because
x ^ x = 0, XORing all numbers together cancels every duplicate pair into0, leaving only the unique number inO(N)time andO(1)memory!
Trick 2: Clearing the Lowest Set 1-Bit (n & (n - 1))
Look at what happens in binary when you subtract 1 from n = 12 (1100):
n = 1100n - 1 = 1011n & (n - 1) = 1000(the rightmost1-bit vanished in one step!).
This gives us two famous interview solutions:
- Count
1-bits (Number of 1 Bits): Loopn = n & (n - 1)untiln == 0. - Dynamic Programming on Bits (
Counting Bits): For every numberifrom1..N,ihas the exact same1-bits asi & (i - 1), plus one more1-bit:dp[i] = dp[i & (i - 1)] + 1!
Interactive Step-by-Step Trace: XOR Cancellation & Brian Kernighan's Trick
See how XOR cancels duplicates and n & (n - 1) drops the lowest set bit:
XOR is commutative and associative: every pair cancels to 0, leaving the single number!
3. Basic Operations & Walkthroughs (All 4 Languages)
# 1. Basic Bit Operations on n = 12 (binary 1100)
n = 12
bit_2 = (n >> 2) & 1 # Read bit 2 -> 1
set_bit_0 = n | (1 << 0) # Turn ON bit 0 -> 13 (1101)
clear_bit_2 = n & ~(1 << 2) # Turn OFF bit 2 -> 8 (1000)
# 2. XOR Cancellation: Find unique number in O(N) time, O(1) space
def single_number(nums: list[int]) -> int:
ans = 0
for x in nums:
ans ^= x
return ans
# 3. Clear Lowest Set Bit: Count 1-bits in O(popcount)
def hamming_weight(n: int) -> int:
bits = 0
while n:
n &= n - 1
bits += 1
return bits4. Core Interview Patterns & Common Traps
Use XOR whenever duplicate pairs cancel to 0 in O(1) space; use i & (i - 1) to strip the lowest set 1-bit in O(1).
# 1. Missing Number in [0..n] via Index-Value XOR:
ans = len(nums)
for i, x in enumerate(nums):
ans ^= i ^ x
# 2. Counting Bits for 0..n in O(N) time:
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i & (i - 1)] + 1| Operation / Pattern | Time | Space | Notes |
|---|---|---|---|
| XOR Pair Cancellation | O(N) | O(1) | x ^ x = 0 and x ^ 0 = x |
| Count Set Bits via n & (n - 1) | O(set bits) | O(1) | At most 32 steps for 32-bit integers |
| Counting Bits 0..N (DP + Bit Trick) | O(N) | O(N) | dp[i] = dp[i & (i - 1)] + 1 |
5. Practice On Your Own (Curated Submodule Problems)
| Status | Problem | Difficulty | Complexity | Hint? | Links & Notes |
|---|---|---|---|---|---|
Single Number XOR Cancellation (x ^ x = 0) | Easy | T: O(N) S: O(1) | |||
Number of 1 Bits Clear Lowest Set Bit (n & (n - 1)) | Easy | T: O(1) S: O(1) | |||
Counting Bits Clear Lowest Set Bit (n & (n - 1)) | Easy | T: O(N) S: O(N) | |||
Missing Number XOR Cancellation (x ^ x = 0) | Easy | T: O(N) S: O(1) |