A complete README-style roadmap for Bit Manipulation, starting from foundation concepts to competitive programming level.
Goal: Understand operators + basic tricks + build intuition
Use: check bit / mask filtering Formula:
n & (1 << i)Checks whether the i-th bit is set.
Use: set bit Formula:
n | (1 << i)Sets the i-th bit to 1.
Use: toggle / difference / unique element
x ^ 0 = x
x ^ x = 0
x ^ y ^ x = yFlips all bits.
~nFormula:
n << k = n * 2^kFormula:
n >> k = n / 2^kif(n & 1) odd
else even(n & (1 << i)) != 0n = n | (1 << i)n = n & ~(1 << i)n = n ^ (1 << i)(n > 0) && ((n & (n - 1)) == 0)while(n){
cnt += (n & 1);
n >>= 1;
}n = n & (n - 1)ans ^= arr[i]All duplicates cancel out.
Goal: Apply XOR + masks + patterns in interview problems
Formula:
xr = a ^ b
setBit = xr & -xrSplit numbers into 2 groups using rightmost set bit.
ans = 0;
for(int i=0;i<=n;i++) ans ^= i;
for(auto x:arr) ans ^= x;Pattern:
n % 4 == 0 -> n
n % 4 == 1 -> 1
n % 4 == 2 -> n+1
n % 4 == 3 -> 0xor(all elements) ^ xor(1..n-1)while(n){
n = n & (n - 1);
cnt++;
}Time = O(number of set bits)
DP Formula:
dp[i] = dp[i >> 1] + (i & 1)for(int mask=0; mask<(1<<n); mask++)if(mask & (1 << i))Loop through all masks and sum selected bits.
Repeatedly remove rightmost set bit:
while(right > left)
right = right & (right - 1);Use Trie + bit traversal.
Sort array and compare adjacent pairs.
a ^= b;
b ^= a;
a ^= b;x = a ^ b;
(x & (x - 1)) == 0Goal: Master optimization + subset DP + advanced XOR
Store binary bits from MSB → LSB.
Formula idea: For each bit, try opposite bit.
Prefix XOR concept:
xr ^= arr[i]Formula:
prefixXor ^ kUse hashmap frequency.
State:
dp[mask][city]State:
dp[mask]Classic formula:
dp[mask] = min(dp[mask], dp[mask ^ (1<<i)])Formula:
for(int i=0;i<n;i++)
for(int mask=0;mask<(1<<n);mask++)
if(mask & (1<<i))
dp[mask] += dp[mask ^ (1<<i)];Split into two halves and use subset sums.
for(int sub = mask; sub; sub = (sub - 1) & mask)while(b){
if(b & 1) ans *= a;
a *= a;
b >>= 1;
}ans = (ans * a) % modFormula:
gray = n ^ (n >> 1)Used in XOR convolution / FWT.
Use Trie + bit counting.
- XOR Basics
- Power of 2 Check
- Single Number
- Brian Kernighan
- Generate Subsets
- Maximum XOR
- Count Subarray XOR
- Bitmask DP
- Gray Code
- Binary Exponentiation
- XOR basics
- set/clear/toggle bit
- single number
- count bits
- subsets
- max XOR
- Trie XOR
- Subarray XOR
- SOS DP
- TSP
- Submask iteration
- Meet in middle
Check bit -> n & (1<<i)
Set bit -> n | (1<<i)
Clear bit -> n & ~(1<<i)
Toggle bit -> n ^ (1<<i)
Remove last set -> n & (n-1)
Power of 2 -> n&(n-1)==0
Gray code -> n^(n>>1)🔥 This roadmap is now in proper README.md format, perfect for:
- GitHub notes
- DSA revision
- OA prep
- Interview prep
- CP practice