Notes
All notes

Bit Manipulation (DSA Core #10)

Bit tricks are not a separate subject. They are a faster way to represent sets, count things, and toggle flags, and they show up in OA problems about parity, subsets, XOR, and state compression. The operations are four, and the rest is recognizing which invariant they give you.

Binary representation

An int is 32 bits, a long long is 64. Bit 0 is the least significant. The value of bit i is \(2^i\).

int x = 13;        // 0b1101 = 8 + 4 + 1
x & 1;             // 1  (odd)
x >> 1;            // 6  (0b110)
Type Bits Range
int 32 \(-2^{31}\) to \(2^{31}-1\)
unsigned int 32 \(0\) to \(2^{32}-1\)
long long 64 \(-2^{63}\) to \(2^{63}-1\)

Negative numbers use two’s complement: -x is ~x + 1. That makes addition work without a separate sign rule, and it is why -1 is all ones. It also means the bit pattern of -1 shifted right is not “half of negative one” — see the signedness section.

Hex is the shorthand: each hex digit is four bits, so 0xFF is 255, 0xDEADBEEF is a 32-bit pattern, and 0xFFFFFFFFFFFFFFFF is -1 as a signed 64-bit value.

QQuestionWhat is ~0 as a signed 32-bit integer?
ASolution

-1. Flipping all zeros gives all ones, which is -1 in two’s complement.

AND, OR, XOR, NOT

a b a&b a\|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

x ^ y has a useful reading: it is the set of positions where x and y differ, so __builtin_popcount(x ^ y) is the Hamming distance.

The three properties that make XOR a tool:

\[ a \oplus a = 0, \qquad a \oplus 0 = a, \qquad a \oplus b \oplus a = b \]

XOR is its own inverse, which is why “find the element that appears once” works without extra memory.

QQuestionWhy is XOR used for toggling rather than AND/OR?
ASolution

x ^ 1 flips a bit regardless of its current value. AND only clears and OR only sets; neither can invert.

Shifts

x << k multiplies by \(2^k\); x >> k divides by \(2^k\) for non-negative x. Shifting is cheaper than multiplication and is exact until bits fall off the end.

1 << 10;           // 1024
1LL << 40;         // 1099511627776, needs the LL suffix
x << 3;            // x * 8

Two rules that bite:

So cast to unsigned when you want a logical shift and to signed when you want sign extension. And never use >> on a negative number for arithmetic unless you have checked the sign separately.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.52cm, font=\scriptsize\ttfamily}]
  \foreach \b [count=\i from 0] in {0,0,0,0,1,1,0,1} {
    \node[c, fill=blue!10] at (7.2-\i*0.55,0) {\b};
    \node[font=\tiny, text=black!55] at (7.2-\i*0.55,-0.42) {\i};
  }
  \node[font=\scriptsize, anchor=east] at (-0.15,0) {13 =};
  \node[font=\scriptsize, anchor=west] at (7.65,0) {bit 0 is the rightmost};
\end{tikzpicture}
QQuestionWhy is 1 << 31 a problem when assigned to int?
ASolution

It sets the sign bit, so the resulting value is -2147483648. If you wanted 2147483648, use 1LL << 31.

Setting, clearing, toggling, testing

Four masks, one per operation:

int setBit(int x, int k)    { return x | (1 << k); }
int clearBit(int x, int k)  { return x & ~(1 << k); }
int toggleBit(int x, int k) { return x ^ (1 << k); }
bool testBit(int x, int k)  { return (x >> k) & 1; }

testBit is written as (x >> k) & 1 rather than x & (1 << k) so the result is 0 or 1, not 0 or \(2^k\). Both are true/false in a condition, only the first is safe to compare.

Masks for ranges:

int lowBits(int k)  { return (1 << k) - 1; }              // bits 0..k-1
int rangeMask(int l, int r) {                             // inclusive
    return ((1 << (r - l + 1)) - 1) << l;
}

Overflow again: (1 << k) - 1 is fine for k <= 30 in int, wrong for k = 31. Use 1LL when k can reach 31 or 63.

QQuestionWhat does x & (x - 1) do, and why?
ASolution

It clears the lowest set bit. Subtracting 1 borrows through the trailing zeros and turns the lowest 1 into 0, leaving everything above it unchanged; ANDing removes that bit.

Counting set bits

Four ways, in increasing order of cleverness:

int popcountNaive(unsigned x) {
    int c = 0;
    while (x) { c += x & 1; x >>= 1; }
    return c;
}
int popcountKernighan(unsigned x) {
    int c = 0;
    while (x) { x &= x - 1; ++c; }     // one iteration per set bit
    return c;
}
int popcountBuiltin(unsigned x) { return __builtin_popcount(x); }
int popcount64(unsigned long long x) { return __builtin_popcountll(x); }

Kernighan’s loop runs once per set bit, so it is \(O(\text{popcount})\) rather than \(O(32)\). __builtin_popcount compiles to a single instruction on x86 (POPCNT) with -mpopcnt, and to a table lookup otherwise.

For a range, build a prefix table instead of calling popcount per query:

vector<int> pre(n + 1, 0);
for (int i = 0; i < n; ++i) pre[i + 1] = pre[i] + __builtin_popcount(i);

The parallel version (for a 64-bit word) uses the SWAR trick x = x - ((x >> 1) & 0x5555...) and so on; it is worth recognizing but not worth writing in an OA.

QQuestionWhy is Kernighan’s method faster than the naive loop on sparse

numbers?

ASolution

The naive loop always shifts 32 times. Kernighan removes one set bit per iteration, so a number with two set bits takes two iterations.

Brian Kernighan’s algorithm

x & (x - 1) is the workhorse:

bool isPowerOfTwo(long long x) {
    return x > 0 && (x & (x - 1)) == 0;
}
int lowestBit(int x) { return x & -x; }

The power-of-two test needs x > 0: zero has no set bits, and 0 & -1 is 0, so it would pass without the guard.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.5cm, font=\scriptsize\ttfamily}]
  \foreach \b [count=\i from 0] in {1,0,1,1,0,0} \node[c, fill=blue!10] at (5-\i*0.55,0) {\b};
  \foreach \b [count=\i from 0] in {1,0,1,0,1,1} \node[c, fill=orange!20] at (5-\i*0.55,-0.8) {\b};
  \foreach \b [count=\i from 0] in {1,0,1,0,0,0} \node[c, fill=green!20] at (5-\i*0.55,-1.6) {\b};
  \node[font=\scriptsize, anchor=east] at (-0.2,0) {x = 44};
  \node[font=\scriptsize, anchor=east] at (-0.2,-0.8) {x-1 = 43};
  \node[font=\scriptsize, anchor=east] at (-0.2,-1.6) {x \& (x-1) = 40};
  \node[font=\scriptsize, anchor=west] at (5.4,-1.6) {lowest set bit removed};
\end{tikzpicture}
QQuestionWhat is x & -x for x = 12 (binary 1100)?
ASolution

0100 = 4, the lowest set bit. -12 in two’s complement flips the bits above the lowest 1 and keeps that 1.

Powers of two and bit length

Useful one-liners:

bool isPow2 = x > 0 && !(x & (x - 1));
int floorLog2 = 31 - __builtin_clz(x);        // x > 0, index of highest bit
int ceilLog2  = x <= 1 ? 0 : 32 - __builtin_clz(x - 1);
int nextPow2  = 1 << ceilLog2;                // careful with 1 << 32

__builtin_clz counts leading zeros; the highest set bit index is width - 1 - clz. For long long, use __builtin_clzll. For x == 0, both are undefined, so guard.

x & (x - 1) == 0 tests “at most one bit set”, which is a power of two only when x > 0. This appears in problems about “can the array be split into groups of size a power of two” and in hashing table sizes.

QQuestionHow do you round x up to the next power of two?
ASolution

Take 1 << ceilLog2(x) (for x not already a power of two). Or use x--; x |= x>>1; x |= x>>2; ...; x++, which is branch-free.

XOR-based tricks

Single number. Every element appears twice except one. XOR everything.

int singleNumber(const vector<int>& a) {
    int x = 0;
    for (int v : a) x ^= v;
    return x;
}

Two singles. Every element appears twice except two. XOR everything to get x = p ^ q, then split by any set bit of x (the two numbers differ there) and XOR each group separately.

pair<int,int> twoSingles(const vector<int>& a) {
    int x = 0;
    for (int v : a) x ^= v;
    int bit = x & -x;                       // any bit where p and q differ
    int p = 0, q = 0;
    for (int v : a) {
        if (v & bit) p ^= v;
        else q ^= v;
    }
    return {p, q};
}

Missing number. 0 ^ 1 ^ ... ^ n cancels with the array values, leaving the missing one. The arithmetic version n(n+1)/2 - sum is equally good and needs no XOR properties.

XOR prefix. pre[i] = a[0] ^ ... ^ a[i-1], then the XOR of [l, r) is pre[r] ^ pre[l]. Same shape as prefix sums, with XOR as the operation.

Swap without a temporary. a ^= b; b ^= a; a ^= b; works but is slower than swap on modern CPUs and breaks if a and b are the same variable. Know it for trivia, not for code.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.62cm, font=\scriptsize}]
  \foreach \v [count=\i from 0] in {4,1,2,1,2} \node[c] at (\i*0.7,0) {\v};
  \node[font=\scriptsize, anchor=west] at (3.75,0) {XOR all = 4};
  \draw[->, thick, orange] (0.35,-0.5) -- (2.65,-0.5);
  \node[font=\scriptsize, anchor=north] at (1.4,-0.55) {duplicates cancel pairwise};
\end{tikzpicture}
QQuestionDoes the single-number XOR trick work if the duplicate values appear

four times?

ASolution

Yes. Four copies XOR to zero, because pairs cancel. It fails only for odd multiplicities other than one, where the leftover is the XOR of the odd-count values.

Bitmasking

A bitmask is a set of small integers packed into one machine word. It gives \(O(1)\) insert, erase, test, and union, and it is the standard representation for “which items are used”.

int mask = 0;
mask |= (1 << i);          // insert i
mask &= ~(1 << i);         // erase i
bool has = mask & (1 << i);
int both = mask1 | mask2;  // union, if the sets are disjoint
int inter = mask1 & mask2; // intersection
int size = __builtin_popcount(mask);

Enumerating all subsets:

for (int mask = 0; mask < (1 << n); ++mask) {
    // mask is a subset of {0..n-1}
}

Enumerating submasks of a mask (useful in partition DP):

for (int sub = mask; sub; sub = (sub - 1) & mask) {
    // sub is a non-empty subset of mask
}

Bitmask DP stores the mask as a state dimension. Task assignment: dp[mask] is the best cost of assigning the first popcount(mask) tasks to the people in mask.

int assignTasks(const vector<vector<int>>& cost) {
    int n = cost.size(), FULL = (1 << n) - 1;
    const int INF = 1e9;
    vector<int> dp(1 << n, INF);
    dp[0] = 0;
    for (int mask = 0; mask <= FULL; ++mask) {
        int person = __builtin_popcount(mask);       // next task to assign
        if (person == n) continue;
        for (int t = 0; t < n; ++t) {
            if (mask & (1 << t)) continue;
            int next = mask | (1 << t);
            dp[next] = min(dp[next], dp[mask] + cost[person][t]);
        }
    }
    return dp[FULL];
}

\(O(2^n \cdot n)\). Practically \(n \le 20\): \(2^{20} \approx 10^6\) states, times 20 transitions is 20 million, which is about a fifth of a second.

The mask is also a visited set in BFS over states (word ladder with wildcards, “minimum flips to reach target”), and a constraint state (Sudoku row/col/box, N-Queens).

QQuestionFor bitmask DP, what does popcount(mask) usually represent?
ASolution

How many decisions have been made. If each decision adds one bit, the count is the stage of the DP, which is why masks can be processed in increasing order.

Signed versus unsigned

unsigned int u = 0;
u - 1;                 // 4294967295, wraps around
int i = INT_MIN;
i = -i;                // undefined behaviour: no positive counterpart
i / -1;                // undefined for INT_MIN

Rules:

For bit work, prefer unsigned or a fixed-width type (uint32_t, uint64_t) when the pattern matters and you intend to shift. For arithmetic, prefer signed and widen to long long before sums and products.

QQuestionWhy is INT_MIN / -1 undefined?
ASolution

The mathematical result \(2^{31}\) does not fit in a 32-bit signed integer, and the hardware traps on x86 for this exact case.

Bugs and edge cases

QQuestionYour subset DP is correct for n = 15 and wrong for n = 31. Why?
ASolution

1 << n overflows a signed 32-bit int at n = 31 (and the mask count is \(2^{31}\), too large anyway). Use 1LL << n and long long masks, and note that \(2^{31}\) states is not feasible regardless.

Next: C++ Data Structures and STL (DSA Core #11) — the containers, their guarantees, and how to pick one in ten seconds.