Skip to main content
Bit Manipulation Pattern

What is Bit Manipulation?

Bit Manipulation uses bitwise operators to solve problems at the binary level. It enables O(1) operations for many tasks and reduces space complexity.

Essential Operations

# Basic operators
a & b   # AND: 1 only if both bits are 1
a | b   # OR: 1 if either bit is 1
a ^ b   # XOR: 1 if bits are different
~a      # NOT: flip all bits
a << n  # Left shift: multiply by 2^n
a >> n  # Right shift: divide by 2^n

Common Tricks

# Check if nth bit is set
(num >> n) & 1

# Set nth bit
num | (1 << n)

# Clear nth bit
num & ~(1 << n)

# Toggle nth bit
num ^ (1 << n)

# Check if power of 2
n > 0 and (n & (n - 1)) == 0

# Get lowest set bit
n & (-n)

# Clear lowest set bit
n & (n - 1)

# Count set bits (Brian Kernighan)
count = 0
while n:
    n &= n - 1
    count += 1

Pattern Variations

1. Single Number

def single_number(nums):
    """Find element that appears once (others twice)"""
    result = 0
    for num in nums:
        result ^= num
    return result

# XOR properties: a ^ a = 0, a ^ 0 = a, commutative

2. Counting Bits

def count_bits(n):
    """Count set bits for all numbers 0 to n"""
    result = [0] * (n + 1)
    for i in range(1, n + 1):
        result[i] = result[i >> 1] + (i & 1)
    return result

3. Subsets Using Bitmask

def subsets(nums):
    """Generate all subsets using bitmask"""
    n = len(nums)
    result = []
    
    for mask in range(1 << n):  # 2^n subsets
        subset = []
        for i in range(n):
            if mask & (1 << i):
                subset.append(nums[i])
        result.append(subset)
    
    return result

4. Missing Number

def missing_number(nums):
    """Find missing number in [0, n]"""
    n = len(nums)
    result = n  # Start with n (might be missing)
    
    for i, num in enumerate(nums):
        result ^= i ^ num
    
    return result

5. Reverse Bits

def reverse_bits(n):
    """Reverse bits of 32-bit unsigned integer"""
    result = 0
    for _ in range(32):
        result = (result << 1) | (n & 1)
        n >>= 1
    return result

Classic Problems

Check: n greater than 0 and (n & (n-1)) equals 0Why: Power of 2 has exactly one bit set
Formula: count set bits in (x ^ y)Why: XOR gives 1 where bits differ
Pattern: sum = a ^ b, carry = (a & b) left-shifted by 1Why: XOR adds without carry, AND gives carry positions
Pattern: Build trie of binary representationsWhy: Greedily choose opposite bit for maximum XOR

Bit Manipulation in DP

def can_partition(nums):
    """Subset sum using bitset DP"""
    bits = 1  # bits represents reachable sums
    
    for num in nums:
        bits |= bits << num
    
    total = sum(nums)
    return total % 2 == 0 and (bits >> (total // 2)) & 1

Common Mistakes

Avoid These Pitfalls:
  1. Signed vs unsigned: Python integers are arbitrary precision
  2. Operator precedence: Use parentheses with bitwise ops
  3. Off-by-one in shifts: Left shifting 1 by 32 may overflow in other languages
  4. Negative numbers: Two’s complement representation

Quick Reference

OperationCodeDescription
Get bit(n >> i) & 1Get ith bit
Set bitn OR (1 left-shift i)Set ith bit to 1
Clear bitn & ~(1 left-shift i)Set ith bit to 0
Toggle bitn ^ (1 left-shift i)Flip ith bit
Lowest bitn & (-n)Isolate lowest set bit
Clear lowestn & (n-1)Remove lowest set bit

Practice Problems

ProblemDifficultyLink
Single NumberEasyLeetCode 136
Number of 1 BitsEasyLeetCode 191
Counting BitsEasyLeetCode 338
Maximum XORMediumLeetCode 421
Interview Tip: XOR is your best friend for “find the unique element” problems. Remember: a ^ a = 0 and a ^ 0 = a.