Skip to main content
Back to the DSA atlas
Bitwise Technique Intermediate

Bit Manipulation

Use bitwise operations for efficient computation. XOR tricks, counting bits, power-of-two checks, and bitmask patterns for subsets and flags.

bit-manipulationmathoptimization

Interactive visualization

Use the controls to connect the idea to concrete operations before diving into the full write-up.

76543210A = 4200101010B = 10501101001^= ?
Processing Result = 1 0 / Inactive

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 O(1)O(1) on fixed-width integers — a single CPU instruction. When you need to track boolean flags, enumerate subsets, or perform arithmetic tricks, bit manipulation replaces O(n)O(n) loops with constant-time expressions and compresses nn booleans into a single integer.

Core operations

Six operations form the basis. All operate independently on each bit position.

OperationSymbolRule
ANDa & b1 only if both bits are 1
ORa | b1 if either bit is 1
XORa ^ b1 if bits differ
NOT~aFlip every bit
Left shifta << kShift bits left by kk, fill with 0
Right shifta >> kShift bits right by kk

Truth table (single-bit):

abANDORXOR
00000
01011
10011
11110

Left shift by kk is equivalent to multiplication by 2k2^k. Right shift by kk is integer division by 2k2^k.

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, nn 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 kk: n | (1 << k)

Clear bit kk: n & ~(1 << k)

Toggle bit kk: n ^ (1 << k)

Check bit kk: (n >> k) & 1

Count set bits (Brian Kernighan): Each iteration of n = n & (n - 1) clears the lowest set bit. Count iterations until n=0n = 0.

count_bits(n):
    count ← 0
    while n > 0:
        n ← n & (n - 1)
        count ← count + 1
    return count

This runs in O(number of set bits)O(\text{number of set bits}), not O(total bits)O(\text{total bits}).

XOR patterns

XOR has three key properties: aa=0a \oplus a = 0, a0=aa \oplus 0 = a, 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. O(n)O(n) time, O(1)O(1) 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 x=abx = a \oplus b. Find any set bit in xx (use x & -x). Partition elements by that bit position and XOR each group separately to recover aa and bb.

Bitmask for subsets

An integer with nn bits represents a subset of {0,1,,n1}\{0, 1, \dots, n-1\}. Bit ii is set if element ii is in the subset.

Enumerate all 2n2^n 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 O(2popcount(mask))O(2^{\text{popcount(mask)}}).

Common interview patterns

ProblemTechnique
Single NumberXOR all elements
Single Number II (appears 3 times)Count bits mod 3 at each position
Hamming Distancepopcount(a ^ b)
Reverse BitsSwap halves recursively or loop through positions
Missing Number (0 to nn)XOR indices with values
Power of Twon & (n - 1) == 0
Subsets generationBitmask from 00 to 2n12^n - 1

Complexity

All single-integer bitwise operations are O(1)O(1). Brian Kernighan’s bit count is O(k)O(k) where kk is the number of set bits (at most O(logn)O(\log n) for value nn). Subset enumeration with bitmask is O(2n)O(2^n).

Key takeaways

  • XOR is the Swiss Army knifea ^ a = 0 and a ^ 0 = a solve “find the unique element” problems in O(1)O(1) 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 nn-bit integer naturally encodes a subset of nn elements, enabling O(2n)O(2^n) enumeration and bitmask DP for NP-hard problems on small inputs.
  • Bitwise operations are O(1)O(1) 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

ProblemDifficultyKey idea
Single Number🟢 EasyXOR all elements — duplicates cancel, leaving the unique value
Number of 1 Bits🟢 EasyBrian Kernighan’s trick: n &= n - 1 counts set bits in O(k)O(k)
Counting Bits🟢 EasyDP using dp[i] = dp[i & (i-1)] + 1 to count bits for every number up to nn
Reverse Bits🟢 EasyLoop through 32 positions, shifting result left and extracting each bit
Subsets🟡 MediumUse bitmask from 00 to 2n12^n - 1 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 dp[mask]dp[\text{mask}] 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.

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.