PrepTrack/

PrepTrack

Guides Hub/Bit Manipulation Patterns & Formulas
DSA Masterclass⏱️ 8 min read10 Core Patterns

Bit Manipulation Patterns & Formulas

The 10 foundational bitwise patterns every software engineer must master for DSA and coding interviews.

💡 If you are preparing for DSA, a handful of bit manipulation patterns cover a massive percentage of interview questions. The secret is not blind memorization—it is understanding what the bits are doing under the hood.

Interactive Bitwise Sandbox

Interactive Bitwise Lab & Visualizer

Change numbers or bit indices and watch the bits transform in real-time.

Bit Register for n = 12Binary: 00001100
b7
0
b6
0
b5
0
b4
0
b3
1
b2
1
b1
0
b0
0
Test Bit Manipulation Formula:
Result OutputDecimal: 8
Original (n):00001100 (12)
Operation Mask:00001011
Result:00001000 (8)

💡 Removed the lowest set bit: 12 (1100) & 11 (1011) = 8 (1000)

The 5 Formulas to Memorize First

High-Yield Core
Check Even / Odd
n & 1
Check if i-th bit is set
n & (1 << i)
Set i-th bit
n | (1 << i)
Clear i-th bit
n & ~(1 << i)
Drop Lowest Set Bit
n & (n - 1)
Isolate Lowest Set Bit
n & -n
XOR Cancellation
a ^ a = 0

The Bigger Mental Model: The 4 Operations

Do not memorize these as disconnected formulas. Understand how the 4 basic bitwise operators manipulate masks.

& (AND)KEEP bits (Filter / Mask)
1011 & 0011 = 0011

Useful for checking, masking, and clearing specific bits.

| (OR)FORCE bits to 1
1010 | 0100 = 1110

Useful for turning on / setting specific bits without disturbing others.

^ (XOR)TOGGLE / DIFFERENCE
1010 ^ 0110 = 1100

Useful for toggling state, parity checks, and duplicate cancellation.

~ (NOT)FLIP every bit
~1010 = ...0101

Useful for constructing inverted masks like ~(1 << i).

The 10 Bit Manipulation Patterns (Detailed Breakdown)

Every formula with internal mechanics, visual binary traces, and canonical code snippets.

1

Check whether a number is Even or Odd

n & 1

In binary, every power of 2 ($2^1=2, 2^2=4, 2^3=8$) is inherently even. The only bit contributing an odd value ($2^0=1$) is the least significant bit (bit 0). If bit 0 is 1, the number is odd; otherwise, it is even.

Binary Arithmetic Trace:
5  = 101 -> last bit is 1 -> Odd
6  = 110 -> last bit is 0 -> Even

5 & 1:
  1 0 1 (5)
& 0 0 1 (1)
-------
  0 0 1 != 0 (Odd)
Java Implementation:
if ((n & 1) == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}
Complexity: O(1) time, O(1) space
#Parity#Modulo Alternative
2

Check if the i-th bit is set

(n & (1 << i)) != 0

Left-shifting 1 by i positions creates a mask with a 1 at position i and zeros everywhere else. AND-ing this mask with n yields a non-zero value if and only if bit i is set.

Binary Arithmetic Trace:
n = 5 (binary: 101), check bit 2:
1 << 2:
  0 0 1
  0 1 0  (1 << 1)
  1 0 0  (1 << 2)

Then:
  1 0 1 (5)
& 1 0 0 (4)
-------
  1 0 0 != 0 -> Bit 2 is SET!
Java Implementation:
// Check whether bit i is set (0-indexed)
boolean isSet = (n & (1 << i)) != 0;

// Alternative right-shift version:
boolean isSetShifted = ((n >> i) & 1) == 1;
Complexity: O(1) time, O(1) space
#Bitmasking#State Query
3

Set the i-th bit

n | (1 << i)

Because 0 | 1 = 1 and 1 | 1 = 1, OR-ing with (1 << i) guarantees bit i becomes 1. Because 0 | x = x, all other bits remain identical to their original values.

Binary Arithmetic Trace:
n = 5 (101), set bit 1:
1 << 1 = 010

  1 0 1 (5)
| 0 1 0 (2)
-------
  1 1 1 = 7
Java Implementation:
// Set bit i to 1
n = n | (1 << i);
Complexity: O(1) time, O(1) space
#Bitmasking#State Update
4

Clear the i-th bit

n & ~(1 << i)

The sub-expression ~(1 << i) is the secret: it creates a mask where every single bit is 1 except for bit i, which is 0. AND-ing with this mask zeroes out bit i while leaving all other bits intact.

Binary Arithmetic Trace:
n = 7 (111), clear bit 1:
1 << 1 = 010
~010   = 101 (inverted mask)

  1 1 1 (7)
& 1 0 1 (5)
-------
  1 0 1 = 5
Java Implementation:
// Clear bit i to 0
n = n & ~(1 << i);
Complexity: O(1) time, O(1) space
#Bitmasking#Bit Reset
5

Toggle the i-th bit

n ^ (1 << i)

XOR has the property that 0 ^ 1 = 1 and 1 ^ 1 = 0. Therefore, XOR-ing any bit with 1 flips it, while XOR-ing with 0 preserves it.

Binary Arithmetic Trace:
n = 5 (101), toggle bit 1:
1 << 1 = 010

  1 0 1 (5)
^ 0 1 0 (2)
-------
  1 1 1 = 7 (if toggled again, becomes 5)
Java Implementation:
// Toggle bit i
n = n ^ (1 << i);
Complexity: O(1) time, O(1) space
#XOR#State Flip
6

Remove the lowest set bit (Brian Kernighan)

n = n & (n - 1)

Subtracting 1 from n flips all bits from the rightmost set bit downward. When you compute n & (n - 1), the rightmost 1 and all lower bits become 0, while all higher bits remain unchanged.

Binary Arithmetic Trace:
n = 12 (binary: 1100)
n - 1 = 11 (binary: 1011)

  1 1 0 0 (12)
& 1 0 1 1 (11)
---------
  1 0 0 0 (8) -> rightmost 1 was dropped!
Java Implementation:
// Count number of set bits (Hamming Weight) in O(set bits) time:
int count = 0;
while (n != 0) {
    n = n & (n - 1);
    count++;
}
return count;
Complexity: O(number of set bits) time
#Brian Kernighan#Hamming Weight#LeetCode 191
7

Get / Isolate the lowest set bit

n & -n

Two's complement representation defines -n as ~n + 1. Inverting n and adding 1 flips all bits up to the lowest set bit, leaving only the lowest set bit matching between n and -n.

Binary Arithmetic Trace:
n = 12:
 12 = 0000 1100
-12 = 1111 0100 (two's complement: ~12 + 1)

  0000 1100 (12)
& 1111 0100 (-12)
-----------
  0000 0100 = 4 (the isolated lowest set bit!)
Java Implementation:
// Isolate the lowest set bit
int lowest = n & -n;
Complexity: O(1) time
#Fenwick Tree#Binary Indexed Tree#Two's Complement
8

Check if a number is a power of 2

n > 0 && (n & (n - 1)) == 0

A positive power of 2 (1, 2, 4, 8, 16, 32...) has exactly one set bit in its binary representation. Removing its lowest set bit via n & (n - 1) must result in exactly 0.

Binary Arithmetic Trace:
n = 8 (1000)
n - 1 = 7 (0111)

  1 0 0 0 (8)
& 0 1 1 1 (7)
---------
  0 0 0 0 == 0 -> Is power of 2!

n = 10 (1010)
n - 1 = 9 (1001)

  1 0 1 0 (10)
& 1 0 0 1 (9)
---------
  1 0 0 0 != 0 -> Not a power of 2!
Java Implementation:
public boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}
Complexity: O(1) time, O(1) space
#Powers of 2#LeetCode 231
9

XOR Identity & Cancellation Tricks

x ^ 0 = x and x ^ x = 0

Because XOR is both commutative (a ^ b = b ^ a) and associative ((a ^ b) ^ c = a ^ (b ^ c)), XOR-ing an array where every element appears twice except one causes all duplicate pairs to cancel out to 0.

Binary Arithmetic Trace:
Array: [4, 1, 2, 1, 2]
Re-ordered conceptually:
  (1 ^ 1) ^ (2 ^ 2) ^ 4
=    0    ^    0    ^ 4
= 4
Java Implementation:
// LeetCode 136: Single Number
public int singleNumber(int[] nums) {
    int ans = 0;
    for (int x : nums) {
        ans ^= x;
    }
    return ans;
}

// Java Stream one-liner:
// return IntStream.of(nums).reduce(0, (a, b) -> a ^ b);
Complexity: O(n) time, O(1) space
#Single Number#LeetCode 136#LeetCode 268
10

Swap two numbers using XOR

a ^= b; b ^= a; a ^= b;

Uses the cancellation property of XOR. Step 1 packs both values into a. Step 2 extracts original a into b. Step 3 extracts original b into a.

Binary Arithmetic Trace:
Initial: a = 5, b = 7
1. a = a ^ b  -> a = 5 ^ 7
2. b = b ^ a  -> b = 7 ^ (5 ^ 7) = (7 ^ 7) ^ 5 = 0 ^ 5 = 5
3. a = a ^ b  -> a = (5 ^ 7) ^ 5 = (5 ^ 5) ^ 7 = 0 ^ 7 = 7
Final:   a = 7, b = 5
Java Implementation:
// In-place XOR Swap:
a ^= b;
b ^= a;
a ^= b;

// IMPORTANT NOTE:
// Do not use this in real production code. Modern compilers optimize temp = a; a = b; b = temp; better,
// and XOR swap fails if a and b reference the exact same memory address (a[i] ^= a[i] produces 0).
Complexity: O(1) time, O(1) space
#XOR Swap#Interview Trivia

Quick-Reference Cheat Sheet Table

Ready for quick revision
Problem / GoalFormulaKey InsightCopy
Check if number is Odd/Evenn & 10 = Even, 1 = Odd
Check if i-th bit is set(n & (1 << i)) != 0Non-zero means set
Set i-th bit to 1n | (1 << i)Forces i-th bit to 1
Clear i-th bit to 0n & ~(1 << i)Forces i-th bit to 0
Toggle i-th bitn ^ (1 << i)Flips 0 -> 1 and 1 -> 0
Remove lowest set bitn & (n - 1)Brian Kernighan algorithm
Get lowest set bit (isolate)n & -nUsed in Fenwick trees & BIT
Check if power of 2n > 0 && (n & (n - 1)) == 0Has exactly one 1-bit
Single Number (Unique in pairs)XOR all elementsx ^ x = 0; x ^ 0 = x
Swap two numbersa ^= b; b ^= a; a ^= b;Conceptual trick (avoid in prod)

The Intuition Decision Tree

When you encounter an interview problem involving bits:
       ↓
Are you testing or reading state?
       → Use: n & (1 << i) or n & 1
       ↓
Are you flipping or setting a flag?
       → Use: n | (1 << i) or n ^ (1 << i)
       ↓
Are you eliminating or counting set bits?
       → Use: n & (n - 1)
       ↓
Are you isolating powers of 2 or tree positions?
       → Use: n & -n
       ↓
Are elements appearing in pairs with one exception?
       → Use XOR accumulation: a ^ a = 0