Skip to content
DSA Patterns
Menu
Language

Pattern #25

Bit Manipulation

Recommended

XOR, masks, shifts, and set-bit tricks for O(1) state.

When to use

Pairs cancel, subsets as bitmasks, power-of-two tests, or compact state in DP.

Recognition cues

  • Single number (XOR)
  • Counting bits / power of two
  • Subset DP on masks

Common pitfalls

  • Sign bit / arithmetic vs logical shift confusion
  • Assuming unlimited int width in languages with fixed ints
  • Off-by-one when iterating bits 0..n-1

90-second recognition drill

Which pattern fits best?

  • Single number (XOR)
  • Counting bits / power of two
  • Subset DP on masks

Interactive

Mental model

A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.

Step 1 of 8
1/8

Single number via XOR: pairs cancel to 0.

4
0
1
1
2
2
1
3
2
4
Stateacc=0 (000₂)

acc = 0

Key:CurrentActive rangeMatchEliminated

How to think about it

XOR is its own inverse: pairs vanish. n & (n-1) drops the lowest set bit. n & -n isolates it. Subset masks belong to bitmask DP. The problems on this path are an XOR fold, a popcount, a power-of-two test, and addition by carry.

Template shapes

Shape Core move Example
Single number Fold XOR from 0. Paired values cancel. The value that appears once remains LC 136
Popcount Kernighan: while n is nonzero, n &= n - 1 drops the lowest set bit and the counter goes up by one LC 191
Power of two A positive power of two has a single set bit: n > 0 && (n & (n - 1)) == 0 LC 231
Missing number XOR 0..n together with every value in nums. The missing number is the value that never paired LC 268
Counting bits dp[i] = dp[i >> 1] + (i & 1). The shift reuses the count without the lowest bit, and i & 1 adds that bit LC 338
Sum without plus XOR is the sum without carry, and (a & b) << 1 is the carry. Repeat until the carry is 0. Python masks to 32 bits so a negative matches two’s complement LC 371

Complexity baseline

O(n) word operations for the fold and the scan. LC 338 fills 0..n in O(n). LC 371 loops once per carry bit.

From template to problem

  1. XOR from 0. Pairs cancel (LC 136). XOR 0..n with the array to leave the missing value (LC 268).
  2. Kernighan drops the lowest set bit with n &= n - 1 (LC 191). A positive power of two is the number that becomes 0 in one such drop (LC 231).
  3. Counting bits reuses dp[i >> 1] and adds the lowest bit. That is the recurrence in the solution, not dp[i & (i - 1)] + 1 (LC 338).
  4. Addition without +: XOR is the sum and (a & b) << 1 is the carry. Python keeps a 32-bit mask so a negative matches two’s complement (LC 371).

Helper identities

Python ints are unbounded. ~n is -n - 1, not a fixed-width bit flip. >> is an arithmetic shift: it floor-divides by 2**k, including for negative numbers. A mask built with n >> 31 assumes a 32-bit int. Bit i is zero-based (i = 0 is the least significant bit).

def is_power_of_two(n: int) -> bool:
    return n > 0 and (n & (n - 1)) == 0

def lowest_set_bit(n: int) -> int:
    return n & -n

def clear_lowest_set_bit(n: int) -> int:
    return n & (n - 1)

def get_bit(n: int, i: int) -> int:
    return (n >> i) & 1

def set_bit(n: int, i: int) -> int:
    return n | (1 << i)

def clear_bit(n: int, i: int) -> int:
    return n & ~(1 << i)

def toggle_bit(n: int, i: int) -> int:
    return n ^ (1 << i)

def popcount(n: int) -> int:
    """Brian Kernighan. n >= 0 only.

    A negative Python int has an infinite string of sign bits, so the
    loop never finishes. For Python 3.10+, n.bit_count() counts the bits
    of abs(n) and accepts negatives.
    """
    if n < 0:
        raise ValueError("popcount loop requires n >= 0")
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count

def single_number(nums: list[int]) -> int:
    """Every value appears twice, except one."""
    acc = 0
    for value in nums:
        acc ^= value
    return acc

def opposite_signs(x: int, y: int) -> bool:
    """True when one value is negative and the other is not.

    Zero counts as non-negative, so zero and a negative are opposite.
    """
    return (x ^ y) < 0

def sign(n: int) -> int:
    return (n > 0) - (n < 0)

def submasks(mask: int):
    """Every bitmask contained in mask, mask itself included."""
    sub = mask
    while True:
        yield sub
        if sub == 0:
            break
        sub = (sub - 1) & mask
a ^ a == 0
a ^ 0 == a
a ^ b == b ^ a
(a ^ b) ^ c == a ^ (b ^ c)
~n == -n - 1

Swap with a, b = b, a. XOR-swap (a ^= b; b ^= a; a ^= b) requires two distinct objects. Applied twice to the same variable, it zeroes it.

INT32_MAX = 2**31 - 1, INT32_MIN = -2**31. These are the 32-bit bounds interviews assume in Java and in languages with fixed ints. They are not a limit in Python. 0xAAAAAAAA and 0x55555555 are 32-bit alternating masks; in Python they are positive values of that width.

Left shift by k multiplies by 2**k. Right shift by k floor-divides by 2**k. (-3 >> 1) == -2 in Python.

Fixed width: TypeScript and C#

TypeScript bitwise operators convert the number to an int32 first. A C# int already is an int32. In both, 1 << 31 is the sign bit, value -2147483648. A shift that must stay positive uses bigint (1n << 31n) or C# long (1L << 31).

>> is an arithmetic shift. >>> is the logical shift, and it fills with zeroes. C# has had >>> since C# 11. .NET 10, which this repo tests with, has it.

The power-of-two test n > 0 && (n & (n - 1)) == 0 is valid for a C# int, and for a TypeScript number only while n is an integer in 1 .. 2**31 - 1. Past that, the bitwise operators look at the low 32 bits. 2**32 + 1 is not a power of two, and the int32 test says it is.

On a long, 1L << 31 is positive and the same power-of-two test accepts it. int.MinValue is one set bit and fails n > 0, so the int test rejects it.

The language cards on this site (/python, /typescript, /csharp) keep the rest of the interview idioms.

Template

Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.

Bit Manipulation · Template
/** Bit template: single number via XOR fold. */
export function singleNumber(nums: number[]): number {
  let x = 0;
  for (const v of nums) x ^= v;
  return x;
}
/** Bit template: single number via XOR fold. */
export function singleNumber(nums: number[]): number {
  let x = 0;
  for (const v of nums) x ^= v;
  return x;
}
#StatusProblemTypeDone
  1. 1#136 Single NumberGuide
  2. 2#191 Number of 1 BitsGuide
  3. 3#231 Power of TwoGuide
  4. 4#268 Missing NumberGuide
  5. 5#338 Counting BitsGuide
  6. 6#371 Sum of Two IntegersGuide