Bit Manipulation
Every integer your program touches is already sitting in memory as a sequence of bits, and a surprising number of "clever" interview problems boil down to noticing that fact. Bit manipulation is the practice of operating directly on those bits with the processor's native bitwise instructions — AND, OR, XOR, NOT, and the two shifts — instead of building auxiliary data structures like hash sets or arrays. Because these operations run in a single CPU cycle and require no extra memory, a good bit trick often turns an O(n) space solution into an O(1) space one without sacrificing time complexity.
The core operators
- AND (
&) — a bit in the result is 1 only if both operands have a 1 there. Used to test or clear specific bits:n & 1checks whethernis odd (its lowest bit is set). - OR (
|) — a bit is 1 if either operand has a 1 there. Used to set specific bits. - XOR (
^) — a bit is 1 if exactly one operand has a 1 there. XOR is the workhorse of this topic because of one property: identical values cancel out. Formally,x ^ x = 0andx ^ 0 = x, and XOR is commutative and associative, so ina ^ b ^ athe twoas annihilate each other regardless of order, leavingb. This is exactly how you find a "lonely" element among duplicates without a hash set. - NOT (
~) — flips every bit. Combined with two's-complement arithmetic,~nequals-n - 1. - Shifts (
<<,>>) —x << kmultipliesxby2^k(shifting bits toward higher significance and filling with zeros), whilex >> kdivides by2^k. Shifts are how you walk over individual bit positions one at a time:(n >> i) & 1reads thei-th bit ofn.
A few identities that solve most problems
n & (n - 1)clears the lowest set bit ofn. Repeating this untilnbecomes 0 counts the set bits, and checking whethern & (n - 1) == 0tests whethernis a power of two.n & -nisolates the lowest set bit (because-nis~n + 1in two's complement, every bit below the lowest set bit flips to matchn, and everything above cancels).n & 1checks parity — 1 for odd, 0 for even — and is cheaper thann % 2.x ^ x = 0,x ^ 0 = x— the cancellation trick behind "find the unique element" problems.