Bit Manipulation · Lesson

Bit manipulation, explained: masks, XOR tricks and every pattern

Learn bit manipulation: check and set bits, n & (n - 1), XOR tricks, missing numbers and SOS DP, with templates in Java, Python, C++ and JavaScript.

6 patterns · 25 problems · Java, Python, C++ and JavaScript

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

What bits give you

Every integer is stored as a row of bits. Bit k is worth 2^k, so 13 is 1101 = 8 + 4 + 1. The operators & (and), | (or), ^ (xor), ~ (not), << and >> (shift) work on all the bits at once, in O(1).

A mask is a number with only the bits you care about set. 1 << k has just bit k. With it you can check a bit (n & mask), set it (n | mask), clear it (n & ~mask) and toggle it (n ^ mask). A mask can also stand for a whole set: bit i set means "item i is in".

The identities worth memorising

  • x ^ x = 0 and x ^ 0 = x: equal values cancel, in any order. This is the key to the missing and repeated number family.
  • n & (n - 1) clears the lowest set bit. Loop it to count bits; n & (n - 1) == 0 means n is a power of two.
  • n & -n keeps only the lowest set bit (the "lowbit"), used by Fenwick trees and in splitting groups.
  • n | (n + 1) sets the lowest unset bit.
  • n >> 1 divides by 2 and n & 1 tells you if n is odd.

Signed numbers and your language

Ints are 32-bit two's complement in Java, C++ and JavaScript bitwise operators: the top bit is the sign, and -1 is all ones. >> copies the sign bit in from the left, so -8 >> 1 is -4. In Java and JavaScript, >>> shifts in zeros instead, which treats the bits as unsigned. In C++, use unsigned or uint32_t for that.

JavaScript numbers are doubles, but every bitwise operator first turns them into a signed 32-bit int: 2 ** 31 | 0 is negative, and x >>> 0 reads the same bits as an unsigned number. Python ints never overflow, so ~5 is just -6 and there is no 32-bit wrap: when a problem needs 32-bit behaviour, mask with & 0xFFFFFFFF.

What it costs

OperationTimeSpace
Check, set, clear or toggle bit kO(1)O(1)
Count set bits (n & (n - 1) loop)O(number of set bits)O(1)
XOR of an arrayO(n)O(1)
Visit every subset of n items as a maskO(2^n)O(1)
Every submask of every maskO(3^n)O(1)
Sum over subsets (SOS DP)O(n · 2^n)O(2^n)

Built into your language

Library calls
Integer.bitCount(13);               // 3 set bits
Integer.toBinaryString(13);         // "1101"
Integer.parseInt("1101", 2);        // 13
Integer.numberOfTrailingZeros(8);   // 3
Integer.highestOneBit(13);          // 8
Integer.reverse(n);                 // the 32 bits in reverse order
Long.bitCount(x);                   // for 64-bit values; use 1L << k past bit 30
-8 >> 1;   // -4 (keeps the sign)      -8 >>> 1;  // 2147483644 (shifts in zeros)

Mistakes everyone makes

  • Operator precedence: n & 1 == 0 means n & (1 == 0) in C++ and JavaScript (and does not compile in Java). Always write (n & 1) == 0.
  • Using >> on a negative number when you wanted the bits shifted with zeros: use >>> in Java and JavaScript, or an unsigned type in C++.
  • Overflowing the shift: 1 << 31 is negative and 1 << 32 is not zero in Java (shifts wrap mod 32). Use 1L << k (Java) or 1LL << k (C++) for big k.
  • Forgetting that JavaScript bitwise operators cut numbers to 32 bits: x | 0 on a value above 2^31 changes it.
  • Porting 32-bit tricks to Python without a mask: Python ints are unbounded, so negative numbers have "infinitely many" leading ones and a carry loop never stops.

The 6 patterns, in order

Each one: the idea and template, its variations with a worked example, then problems for you to solve.

  1. 1 Bit basics: read, test and build numbers bit by bit n & 1 reads the lowest bit and n >> 1 drops it, so a loop can walk through every bit. (n >> k) & 1 tests one bit, and res = (res << 1) | bit builds a number one bit at a time. 3 variations · 8 problems
  2. 2 Bit tricks: lowest set bit, powers of two and repeating patterns A handful of one-liners do most of the work: n & (n - 1) clears the lowest set bit, n & -n keeps only it, n | (n + 1) sets the lowest unset bit, and XOR of 1..n repeats every 4 numbers. 3 variations · 7 problems
  3. 3 XOR basics: cancel, compare and prefix XOR XOR is addition without carries: x ^ x = 0, x ^ 0 = x, and order does not matter. That makes it undo itself, mark the bits where two numbers differ, and turn prefix XORs back into the original values. 3 variations · 5 problems
  4. 4 Missing and repeated numbers with XOR XOR everything together and every value that appears twice cancels, leaving the odd one out. Add the indexes too and the missing number is left. With two odd ones out, split by any bit where they differ. 3 variations · 3 problems
  5. 5 Sum over subsets (SOS) DP For every mask, add up the values stored at all of its submasks. Handling one bit at a time does this in O(B · 2^B) instead of O(3^B), and it answers "how many items fit inside this mask?" for every mask at once. 1 variation · 1 problem
  6. 6 Bits meet number theory: gcd and powers of two Some puzzles hide a number theory fact about powers of two. Find what never changes under the allowed moves (here, the odd part of the gcd), then the bit trick g & (g - 1) == 0 answers the question. 1 variation · 1 problem