Skip to content
Tech Interview Prep
Technical interview guide

Bit Manipulation

Working directly on a number's binary representation with AND/OR/XOR/shifts: for O(1) tricks and memory-efficient state.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with integer semantics cited from CPython 3.14, java.util as of Java 21, and the C++ standard library.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-10

Walk me through what a bit and a fixed-width word are, how to read a binary value by hand, and why the width constrains every operation that follows.

Answer

A bit is one binary digit, 0 or 1. A fixed-width word is a fixed count of those bits held in one machine integer (8, 32 or 64 in practice) and the width is what turns a row of bits into a number. A w-bit word has 2^w distinct patterns, and the value is the sum of the place values whose bit is set: 1, 2, 4, 8, 16 … from bit 0 upward. Bit 0 is the least significant and is drawn on the right; the left-to-right string is a display convention, not a statement about how the bytes sit in memory.

Reading by hand, take 0b1011_0101 and add the columns that are set:

bit index76543210
place value1286432168421
1011010110110101

128 + 32 + 16 + 4 + 1 = 181. Writing is the same walk backwards: subtract the largest place value that fits and repeat. 13 = 8 + 4 + 1, so 13 is 0b1101, with bits 3, 2 and 0 set. That round trip is the whole conversion; bin(13) and int('1101', 2) just automate what you can do on a whiteboard.

The frame changes when the word is signed. Two's complement puts the sign bit at position w-1 and reads its place value as negative: in 8 bits, 128 becomes -128. So 0b1011_0101 is 181 unsigned and -75 signed: -128 + 32 + 16 + 4 + 1 = -75, equivalently 181 - 256. To write -75 down: 75 is 0100 1011, invert to 1011 0100, add one, get 1011 0101. Same bits, two readings.

Width decides four things before any operation runs:

wunsigned rangesigned rangesign bit
80 .. 255-128 .. 1277
320 .. 4 294 967 295-2 147 483 648 .. 2 147 483 64731
640 .. 18 446 744 073 709 551 615-9 223 372 036 854 775 808 .. 9 223 372 036 854 775 80763

Truncation and wraparound fall straight out of that table. 300 is 0b1_0010_1100, nine bits; forced into 8 unsigned bits the top bit goes and you get 0b0010_1100 = 44, which is 300 mod 256. In an 8-bit unsigned word 255 + 1 is 0; in an 8-bit signed word -128 - 1 is 127. And the sign bit is 7, 31 or 63 depending on width: anything hard-coding 31 is wrong the day it meets a 64-bit value.

The failure this invites is specific: assuming every language wraps at the width. Java's int is 32-bit two's complement and overflow wraps silently (JLS §4.2.1–4.2.2). C++20 mandates two's complement representation but signed integer overflow is still undefined behaviour. Python 3 ints have unlimited precision, so nothing truncates or wraps unless you ask. It survives code review because the tests were written in the language where the assumption happened to hold.

Python
bin(13)           # '0b1101'
int('1101', 2)    # 13
bin(-75 & 0xFF)   # '0b10110101' - an 8-bit view; Python itself will not truncate

In practice, fix width and signedness before writing the trick, put 0, 2^w - 1 and 2^w in the tests, and make the width explicit in the type wherever code crosses a serialization or language boundary. Shifts, masks and XOR then operate on a frame that is actually defined.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-16

Walk me through bitwise AND, OR, and NOT: truth tables, one worked 8-bit example each, how they mask, set and invert bits, and where they collide with && and ||.

Answer

AND keeps the bits both operands have, OR keeps the bits either operand has, NOT flips every bit of the word. Those three plus a shift build every mask idiom in the catalogue. Assume a fixed-width word and name the width, because NOT is width-relative: on 8 bits ~0x0F is 0xF0, on a 32-bit int it is 0xFFFFFFF0. Which one you get is a property of the integer type, not of the operator.

Truth tables, one row per input pair:

a b | a & b | a | b        a | ~a
0 0 |   0   |   0          0 |  1
0 1 |   0   |   1          1 |  0
1 0 |   0   |   1
1 1 |   1   |   1

NOT is the only unary one here, and it has no counterpart in the two-input tables: it depends on the width of its single operand.

Worked 8-bit examples, one per operator:

AND — isolate the low nibble          OR — turn on bits 0 and 2       NOT — flip 8 bits
  1011 0110   (0xB6)                   1011 0000   (0xB0)             ~ 0000 1111   (0x0F)
& 0000 1111   (0x0F)                 | 0000 0101   (0x05)             = 1111 0000   (0xF0)
= 0000 0110   (0x06)                 = 1011 0101   (0xB5)

The standard uses fall out of those three lines: x & MASK reads bits, x |= MASK sets bits without disturbing the rest, x &= ~MASK clears bits (AND with the complement), and x ^= MASK toggles. Masks themselves come from shifts:

C
/* C11 */
enum { READ = 1u << 0, WRITE = 1u << 1, EXEC = 1u << 2 };  /* single bits */
unsigned low_nibble = (1u << 4) - 1;   /* 0x0F — low n bits */
unsigned perms = READ | WRITE;         /* 0b011 */
if ((perms & EXEC) == 0) { /* not executable */ }
perms |= EXEC;                         /* 0b111 */
perms &= ~WRITE;                       /* 0b101 */

Bitwise versus logical is the part people trip over. & and | operate bit by bit and evaluate both sides; && and || operate on truth values, return a boolean, and short-circuit. flags && 0x0F does not mask anything: it collapses flags to true or false.

The precedence trap is language-specific, and it is worth being exact. In C, C++, Java and C#, == binds tighter than &, so flags & 3 == 3 parses as flags & (3 == 3), i.e. flags & 1: it compiles cleanly and is wrong. Python inverts that: & binds tighter than ==, so the same expression parses as (flags & 3) == 3 and happens to do what it looks like. A bug that reproduces in C is invisible in Python, and a fix written for one does not transfer to the other. Write (flags & 3) == 3 in every language and the question goes away.

The other failure this invites is width: a mask authored at one width used at another. ~0x0F is 0xFFFFFFF0 on a 32-bit int, and in Python 3 integers are unbounded so ~0x0F is -16, not 0xF0: the 8-bit complement needs ~0x0F & 0xFF. It survives casual testing because small values with the high bits clear pass every assertion written by eye.

In practice, name masks as constants built from shifts, parenthesise every bit test, and keep the mask's width equal to the value's width. The conditional part: reach for bit flags only when the option set is small, fixed and often tested in combination. Otherwise an enum or a set says what it means without a decoding step.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-9

What are the exact expressions for getting, setting, clearing, and toggling bit i with the mask (1 << i), and where do engineers get the indexing wrong?

Answer

One mask does all four, and the mask is the only part that changes with position: mask = 1 << i, with i counted from 0 at the least significant bit.

Python
# checked against Python 3.14
def get_bit(x, i):    return (x >> i) & 1
def set_bit(x, i):    return x | (1 << i)
def clear_bit(x, i):  return x & ~(1 << i)
def toggle_bit(x, i): return x ^ (1 << i)

get shifts the bit of interest down to position 0 and masks off everything else. x & mask alone returns the value at its own place (0 or 2**i), so the & 1, or a != 0, is what makes the answer 0/1. set ORs a 1 in, clear ANDs a 0 in, toggle XORs, and XOR flips because 1 ^ b = not b for a single bit.

Worked 8-bit trace, x = 0b10110110 (182). An 8-bit value has bits 0..7, so those are the only legal positions.

operationi = 3, mask 0b00001000i = 2, mask 0b00000100
get01
set0b10111110 (190)0b10110110 (182, unchanged)
clear0b10110110 (182, unchanged)0b10110010 (178)
toggle0b10111110 (190)0b10110010 (178)

Set and clear are idempotent when the bit is already in the target state; toggle never is. That is why toggle is right for a flip control and set/clear are right for assignment.

Why the mask is shifted rather than hard-coded: 0x08 means "bit 3 of an 8-bit value" only where it was typed. 1 << i is derived from the position, so one helper is correct at any width. Shifting also inherits the operand's type: Python ints have unlimited precision so 1 << 200 is just a big number, while a fixed-width type gives the mask its width and signedness.

Clearing means AND with the complement. ~mask is all ones except a zero at i, so AND preserves every other bit and forces bit i to 0. It is not x - mask: subtraction borrows when the bit is already clear. 182 - 8 = 174 (0b10101110), it cleared bit 4 and set bit 3, whereas 182 & ~8 leaves 182 untouched.

The off-by-one is indexing. Bit 0 is the ones place, 1 << 0 == 1. The mistake I look for is a teammate counting from the MSB because the flag diagram was drawn left-to-right, or passing 1-based positions straight from a spec. Guard with 0 <= i < width wherever i comes from outside the function.

The range trap sits next door and is worse. On a 32-bit signed type, 1 << 31 computes 2^31 = 2147483648, which is outside [−2147483648, 2147483647], so the mask lands in the sign bit: Java yields Integer.MIN_VALUE, and ~(1 << 31) then clears the sign bit instead of setting it. Under C11 6.5.7p4 that shift was undefined behaviour; C++20 and C23 define it as two's-complement wraparound. Java masks shift counts to 5 bits so 1 << 32 is 1; Python never wraps. So build the mask in a type wide enough or unsigned (1u << i, 1ULL << i) and validate i before you shift.

In practice, define these four helpers once in a shared module instead of open-coding masks at call sites, keep i inside the type's width, and reach for a real bitset once the universe stops fitting in a machine word.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Explain two's complement representation and how it changes a production decision.

Answer

Core answer

Assume fixed-width integers (8/16/32/64-bit), no arbitrary precision. Two's complement encodes an N-bit signed value as -b(N-1)·2^(N-1) + Σ b(i)·2^i: the top bit carries weight -2^(N-1), it is not a sign flag. The range is asymmetric, -2^(N-1) to 2^(N-1)-1, so the most negative value has no positive counterpart.

The production decision this changes is any counter, accumulator, timestamp or ID that can grow: two's complement fixes the wrap point and makes the wrap silent, so the decision is width + signedness + overflow policy, not "does it fit today".

Mechanism

Addition is mod 2^N with carry-out discarded, which is why one adder serves signed and unsigned. Negation is ~x + 1.

Python
def add8(a, b): return (a + b) & 0xFF

add8(0x7F, 0x01)   # 127 + 1      -> 0x80 -> -128
add8(0xFF, 0x01)   # -1 + 1       -> 0x00 -> 0
add8(0x80, 0x80)   # -128 + -128  -> 0x00 -> 0
(~0x80 + 1) & 0xFF # -(-128)      -> 0x80 -> -128
WidthRangeWrap
int8-128 .. 127127+1 = -128
int16-32,768 .. 32,767
int32-2,147,483,648 .. 2,147,483,647
int64-9.22e18 .. 9.22e18

Alternatives

Sign-magnitude and ones' complement both have two zeros and need separate sign logic or end-around carry; two's complement won because it reuses the unsigned adder. Saturating arithmetic clamps instead of wrapping (DSP, media codecs): right when a clipped value is safer than a wrapped one. Arbitrary precision (Java BigInteger, Python int) never wraps but allocates and is 10-100x slower per op. Unsigned gives 0 .. 2^N-1, but subtraction underflow wraps to a huge positive.

Failure modes

  • Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE (Java). Detect with a unit test on MIN_VALUE.
  • Binary-search midpoint (lo + hi) / 2 overflows for large arrays; use lo + (hi - lo) / 2.
  • C/C++ signed overflow is undefined behaviour: the compiler may assume it never happens and delete your check. Detect with -fsanitize=signed-integer-overflow; -fwrapv forces wrap.
  • Rust panics on overflow in debug, wraps silently in release. A bug that only appears in production. Set overflow-checks = true in the release profile.
  • An int32 millisecond timestamp wraps at 2,147,483,647 ms ≈ 24.85 days.

The decision

You are sizing a per-tenant request counter at 10k req/s. int32 wraps at 2,147,483,647 → 2.49 days. Two's complement makes that wrap silent and sign-flipping: the counter goes negative, and counter < limit now passes forever. So the decision is int64 (9.22e18 → ~29 million years at 10k/s), signed, with an explicit counter >= 0 assertion. Unsigned int32 is not the fix: it wraps to 0, which a rate limiter also reads as "under limit". Signedness changes which wrong answer you get; width changes whether you get one at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about the asymmetric integer range in a system you own?

Answer

Core answer (first 90 seconds)

Two's complement gives a signed 32-bit int the range −2,147,483,648 to 2,147,483,647: one more negative than positive, because zero takes a slot on the positive side. The consequence is that -INT_MIN and abs(INT_MIN) have no representable result. In a system I own, the range itself is not the question: the question is whether an unbounded value (a hash, a difference of two timestamps, a parsed wire field) can reach a negation or an absolute value, and what my language does when it does. So I work in three steps: find the reachable sites, check the language's contract at each, then choose between handling the minimum, widening the type, or removing the negation.

What each language actually guarantees

Languageabs(INT_MIN)Notes
C / C++undefined behaviourC11 7.22.6.1; -INT_MIN is signed overflow, also UB
Javareturns Integer.MIN_VALUEdocumented on Math.abs(int); Math.absExact (Java 15+) throws ArithmeticException
Rustdebug: panic; release: returns i32::MINchecked_abs → None, unsigned_abs → u32
Pythoncorrectarbitrary precision, no fixed width

The Java row is the one that bites: Math.abs is total, so it never throws and never warns. It hands back a negative number the caller assumed was non-negative.

The failure mode I actually look for

The classic is a hand-rolled hash-to-bucket:

Java
int bucket = Math.abs(key.hashCode()) % table.length;

If key.hashCode() returns Integer.MIN_VALUE, Math.abs returns Integer.MIN_VALUE, and % in Java keeps the sign of the dividend, so bucket is negative → ArrayIndexOutOfBoundsException, or a negative index into a structure that silently accepts it. HashMap sidesteps this by masking ((n - 1) & hash) rather than taking an absolute value. The same shape shows up in sort keys ("distance from zero"), in abs(a - b) comparisons where a - b can itself overflow before abs runs, and in C where abs(INT_MIN) is UB and the optimiser is entitled to delete the branch you wrote to handle it.

Deciding what to do

  • If the domain is bounded (an age, a port, a percentage), the asymmetry is unreachable: document the bound and move on. Don't add a branch you can't test.
  • If the value is unbounded (hash, timestamp difference, wire input), pick one: handle the minimum explicitly, widen to a type that can hold it (long, unsigned_abs, BigInteger), or drop the negation entirely. Compare a < b directly, or compare sign then magnitude.
  • Widening costs memory and cache; a branch costs at most a predictable mispredict. On a hash path, masking is cheaper than both.

Audit sequence for a codebase I own

  1. Grep for abs(, Math.abs, -x on non-constant ints, and % applied to an abs result.
  2. For C/C++, run -fsanitize=undefined (catches negation overflow) and -ftrapv in CI.
  3. For Java, add a boundary test asserting Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE at each site, or switch to Math.absExact and let it throw.
  4. Property-test comparators for antisymmetry and transitivity with MIN_VALUE in the input set: a broken abs-based comparator is silent otherwise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Walk through arithmetic versus logical shift, including where engineers most often get it wrong.

Answer

The 90-second answer

There are two right shifts and one left shift. Arithmetic right shift replicates the sign bit; logical right shift fills with zero. Left shift is the same operation either way, it always shifts in zeros, so "arithmetic versus logical" is only a real question for right shift.

Which one you get depends on the language and the operand type, and that is the first place engineers get it wrong: they assume >> is logical because that is what it does on unsigned values, then apply it to a signed one.

Mechanism

On a two's-complement signed value the top bit is the sign. Arithmetic right shift copies it down, which is exactly floor division by 2^n. Logical right shift shifts in zeros, reinterpreting the bit pattern as unsigned.

Trace, 32-bit Java ints, x = -7:

expressionbit patternvalue
x0xFFFFFFF9-7
x >> 10xFFFFFFFC-4
x >>> 10x7FFFFFFC2147483644

Same input, same width, two operators, two answers. >>> is not "divide by two" for negative inputs: it is a bit-pattern operation that happens to coincide with division for non-negative values.

Python has only >>, and it is arithmetic on ints of arbitrary width. There is no logical shift operator; you emulate it by masking to a width first:

Python
x = -7
x >> 1                  # -4
(x & 0xFFFFFFFF) >> 1   # 2147483644, matches Java's >>>

Where it goes wrong

  1. Rounding direction. -7 >> 1 is -4, but int(-7 / 2) is -3. Arithmetic shift rounds toward negative infinity; C-style integer division truncates toward zero. Code that uses >> as a fast divide is correct for non-negative inputs and off by one for negative ones. It survives testing because test data is usually non-negative.

  2. Assuming >> is logical. In C and C++, right shift of a negative signed value is implementation-defined (C++20 defines it as arithmetic; C still leaves it implementation-defined). Java, JavaScript and Python all define >> as arithmetic. Rust has no logical shift on signed integers at all: you cast to the unsigned type.

  3. Shift counts at or beyond the width. Java masks the count mod 32, so x << 32 == x. C and C++ make it undefined behaviour. Neither matches what a reader assumes.

  4. Left shift. There is no arithmetic/logical distinction, but a signed left shift that overflows is undefined behaviour in C and C++.

What to do

If you need division, write division: the compiler emits the shift when it is safe. If you need a bit pattern, use the unsigned type or an explicit mask, so width and signedness live in the code rather than in your head.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does shift amounts outside the width guarantee, and what does it deliberately leave open?

Answer

The 90-second answer

A shift count at or above the width guarantees nothing about the value. What it guarantees is only that you have stepped outside the language's defined semantics, and how far outside depends on which language you are in.

C and C++ call it undefined behavior (C11 6.5.7p3, C++ [expr.shift]): the count must be less than the width of the promoted left operand. UB means the compiler may assume it never happens: it can delete the branch you wrote to catch it, fold the expression to any value, or emit a shift instruction that does something platform-specific. Nothing is guaranteed, not the result and not that the program is well-formed.

Java and C# go the other way and define it: the count is masked to the low bits of the width. 5 bits for int, 6 for long. So 1 << 32 is 1, not 0, and 1 << 33 is 2. Fully specified, and almost never what the author meant.

What is deliberately left open is the value itself. The masking languages leave the semantics open: you get a defined but surprising number. The UB languages leave everything open, including whether your guard survives the optimizer.

Why the two camps differ

The masking languages are codifying what the hardware already does. x86's shl/shr take the count from cl and use only its low 5 bits (6 for 64-bit operands). Java's spec just writes that down. C refuses to, because the hardware disagrees across architectures, so the same source is UB everywhere and behaves differently everywhere.

LanguageCount ≥ width1 << 32 on a 32-bit int
C / C++undefined behavioranything; compiler may warn and fold
Javamasked to low 5 bits1
C#masked to low 5 bits1
Rustpanic in debug; masked in release1 (release)
Pythonno width, arbitrary precision4294967296

The same C line, two architectures

C
int shift(int x, unsigned n) { return x << n; }   /* n >= 32 is UB */

On x86-64, gcc -O2 emits shl %cl, %eax; the CPU masks cl to 5 bits, so shift(1, 32) returns 1. On 32-bit ARM, LSL by register uses the low byte of the shift register, so a count of 32 is not masked down: every bit shifts out and shift(1, 32) returns 0. Same source, same UB, two answers. The language left it open and the hardware filled the gap differently.

Guarding versus widening

  • Guard: if (n >= 32) return 0;. One branch, ~1 cycle when predicted. You still have to pick the semantics: zero, saturate, or error. If n is data-dependent and unpredictable, a mispredict costs ~15–20 cycles, which dwarfs the 1-cycle shift it protects.
  • Widen: move to uint64_t and shift by up to 63. Doubles register pressure and buys one more bit of headroom; it does nothing for a count that can exceed 64.
  • Arbitrary precision: Python's 1 << 100 allocates a new object, so a one-cycle shift becomes tens of nanoseconds plus GC pressure. Reach for it when the values genuinely exceed 64 bits, not to dodge a bounds check.

The decision rule: if the count is a compile-time constant, assert it (static_assert(n < 32)) and pay nothing. If it is data-dependent, decide the out-of-range semantics explicitly and write the branch: the branch is cheaper than the bug.

Failure modes and how to catch them

  • C/C++ UB: the compiler assumes n < 32, so if (n < 32) x <<= n; can be optimized to x <<= n;. Your guard is deleted. Catch it with UBSan: -fsanitize=undefined reports shift exponent 32 is too large for 32-bit type 'int' at runtime, and -Wshift-count-overflow catches the literal case at compile time.
  • Java/C# masking: a bit-packing or hashing routine that shifts by a variable count silently produces wrong bits the moment the count reaches the width. It passes every test where the count is small. Catch it with a test that pins the count to exactly the width and to width + 1.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does overflow behaviour force that a junior answer usually skips?

Answer

The trade-off is between cheap arithmetic and being able to detect overflow where it happens. You get one or the other, not both for free.

If a language defines overflow (wrapping, trapping, or arbitrary precision) every arithmetic operation carries a cost: a branch, a flag test, or a wider representation. If it declares signed overflow undefined (C and C++ do), the compiler is entitled to assume it never happens. That assumption is what unlocks induction-variable widening, range-based vectorization, and deletion of redundant checks. The price is that any overflow check written after the operation is dead code, because the compiler has already proved the condition false.

That is the part a junior answer skips. "It's UB" or "it wraps" is a fact; the trade-off is that UB buys speed by removing your ability to check, so the check has to move before the operation or into a checked API.

Mechanism: with int i, for (i = 0; i <= n; i++). The compiler assumes i never overflows, so it can widen i to 64-bit, drop the per-iteration comparison against n, and vectorize. If overflow were defined, it would have to preserve the wrap and keep the comparison. Same source, different loop.

LanguageSigned overflowCost of detection
C / C++undefinedUBSan, -fwrapv, -ftrapv; check before the op
Rustpanics in debug, wraps in releasechecked_add returns Option; overflow-checks in release
Javawraps silentlyMath.addExact throws; slower
Gowraps (defined)manual checks; no trap
Swifttraps by default&+ to opt into wrapping
Pythonnone (bigint)allocation plus O(n) per op

Check before, not after:

C
#include <limits.h>
/* returns 0 on success, -1 on overflow */
int add_checked(int a, int b, int *out) {
    if (b > 0 && a > INT_MAX - b) return -1;
    if (b < 0 && a < INT_MIN - b) return -1;
    *out = a + b;
    return 0;
}

Trace: a = INT_MAX (2147483647), b = 1. b > 0, INT_MAX - b = 2147483646, a > that → return -1. No addition performed, no UB. a = 100, b = 200: 100 > 2147483447 is false, b is not negative, so *out = 300, return 0.

The after-check version if (a + b < a) is exactly what the optimizer deletes at -O2: it assumes a + b did not overflow, so a + b < a is false.

Rust makes the choice explicit:

Rust
let a: i32 = i32::MAX; // 2147483647
a.wrapping_add(1)   // -2147483648
a.checked_add(1)    // None
a.saturating_add(1) // 2147483647

Three behaviours, three costs: wrapping is a single add; checked_add compiles to an add plus an overflow-flag branch; saturating_add needs a conditional move.

Failure modes:

  • Deleted after-check → silent wrong result. A length len + 1 wraps negative, gets cast to size_t, becomes ~2^64, and the allocation or memcpy overruns. Detected by UBSan in CI, not by unit tests on small inputs.
  • Debug/release divergence in Rust: tests panic in debug, production wraps silently. Detected by running the suite with overflow-checks = true in the release profile, or cargo test --release.
  • Java: silent wrap in production; Math.addExact throws but is rarely used on hot paths.

When not to pay: if the domain bounds the inputs (a counter that cannot exceed 10^6), the check is dead weight. Document the bound instead. If you need unbounded values, bigint removes the question but costs an allocation and O(n) per op.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe arbitrary-precision integers and the evidence you would collect before relying on it.

Answer

What a strong candidate says first

Arbitrary-precision integers are exact integers whose width is bounded only by memory. The implementation is a sign plus an array of fixed-size limbs, CPython uses 30-bit digits on 64-bit builds, with carry propagation between limbs. Addition is O(n) in limb count; multiplication is superlinear (schoolbook O(n²), Karatsuba above a cutoff of 70 digits in CPython's longobject.c). Nothing overflows, but nothing is free: cost, memory and timing all scale with the value. So the evidence you collect is about the implementation you actually have, at the sizes you actually hit.

1. A primary source that the type is unbounded. Python's docs say integers have unlimited precision; Java's BigInteger javadoc and Go's math/big say the same for their types. Note which is the default: Python's int is arbitrary precision, Java's long and Go's int are not, so the same algorithm ports across with different overflow behaviour.

2. The implementation's own parameters. Ask the runtime rather than trusting a blog post:

Python
import sys
sys.int_info
# sys.int_info(bits_per_digit=30, sizeof_digit=4, default_max_str_digits=4300)

len(str(10**4299))   # 4300  (1 followed by 4299 zeros)
str(10**4300)        # ValueError: Exceeds the limit (4300 digits) for integer string conversion

That last line is a real failure mode: since CPython 3.11 (backported to 3.10.7/3.9.14) decimal conversion of a huge int raises unless you call sys.set_int_max_str_digits(). Logging or JSON-serialising a big value can fail where the arithmetic succeeded.

3. Memory per value, measured. 10**5000 is about 16,610 bits, so ~554 limbs of 30 bits at 4 bytes each: roughly 2.2 KB plus a fixed header. Confirm with sys.getsizeof; the arithmetic predicts, the call reports.

4. A benchmark at your digit sizes. Multiplication cost grows with operand length, so a loop that accumulates a product is quadratic in the number of iterations. Time the actual workload at the actual sizes; a microbenchmark on 64-bit values tells you nothing about 10,000-digit ones.

5. Constant-time behaviour, if any value is secret. CPython's integer arithmetic is not constant-time and its timing depends on operand magnitude. For keys or tokens, use a crypto library's fixed-width or constant-time primitives, not int.

6. Interop at the boundaries. JSON parsers in other languages may truncate; protobuf has no native bigint, so it goes over the wire as a string or bytes; Postgres needs NUMERIC, not BIGINT.

LanguageDefault integerArbitrary precision
Pythonarbitrary precisionbuilt in (int)
Java64-bit longjava.math.BigInteger
Go64-bit intmath/big.Int
Rust64-bit i64num-bigint crate
C32/64-bitGMP, or nothing

7. Tests that would catch the failure. Property tests against a reference implementation, boundary cases at 2^63 and 2^64, and round-trip serialisation tests through every boundary in item 6. The bug that survives casual testing is the one where the happy path never reaches the size that breaks.

Failure modes to name. Silent truncation at a serialisation boundary; ValueError on decimal conversion; quadratic blowup in an accumulation loop; timing leakage when the value is a secret. Each is detected differently (round-trip tests, a log line, a profile, a timing harness) which is why "it's arbitrary precision, so it's safe" is not an answer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

What breaks when bit tricks meet real languages and real data, and what does bitwise code that survives those hazards actually look like?

Answer

Assume fixed-width machine integers in C, C++ and Java. Python is the counterexample: its ints are arbitrary precision, the docs say unlimited precision, so 1 << 31 is 2147483648 there and none of the hazards below exist. Port the same code to C or Java and four different things go wrong.

Almost every broken bitwise routine I have reviewed got one of these wrong: the shift count, the signedness of the operand, promotion of a narrow type, or an assumed width. The defense is one rule and a test table: every operand is an explicit unsigned fixed-width type, every shift count is provably less than its width, and the boundary values are exercised.

Shift counts. In C and C++, shifting by a count greater than or equal to the width of the promoted left operand is undefined behaviour (C11 6.5.7p4). Java masks the distance instead: for int only the low five bits are used, so 1 << 32 is 1, not a crash and not 0.

expressionC11C++14 and laterJava 21Python 3.14
1 << 32 (32-bit int)undefinedundefined1 (n & 31)4294967296
1 << 31undefinedINT_MINInteger.MIN_VALUE2147483648
-1 >> 1implementation-defined (arithmetic in practice)same-1 (arithmetic)-1
-1 >>> 1no such operatorno such operator0x7FFFFFFFno such operator

The same shape in both languages:

C
// before: width == 32 is undefined in C/C++, and in Java (1 << 32) - 1 == 0,
// so the mask silently accepts nothing
uint32_t mask = (1 << width) - 1;
// after
uint32_t mask = width >= 32 ? UINT32_MAX : (UINT32_C(1) << width) - 1;

The sign bit. 1 << 31 on a signed int is undefined in C11 because 2^31 is not representable in the result type; C++14 and later define it as INT_MIN, and Java defines it as Integer.MIN_VALUE. Write 1u << 31 (or UINT32_C(1) << 31) and keep flag work unsigned so every shift is a logical one. >> on a negative operand is implementation-defined in C and C++ (arithmetic on GCC, Clang and MSVC) and defined as sign-extending in Java, where >>> is the zero-filling form.

Sign extension, traced. With int8_t b = 0x80:

b >> 4                     // -8          arithmetic shift, sign extended
(uint32_t)(b >> 4)         // 0xFFFFFFF8  widened after the shift
((uint32_t)b & 0xFFu) >> 4 // 0x08        widened and masked before

Java's >>> does not rescue you here: ((byte)0x80) >>> 4 is 0x0FFFFFF8, because the byte was promoted to int before the shift. Only b & 0xFF first is correct.

Promotion of narrow types. ~, <<, - and the binary operators promote a uint8_t to int:

C
uint8_t  flags  = 0x80;
uint8_t  narrow = ~flags;            // 0x7F — assignment truncation hides the bug
uint32_t wide   = ~flags;            // 0xFFFFFF7F
uint32_t right  = ~flags & 0xFFu;    // 0x7F

So name the width: constexpr uint8_t kFlagsMask = 0xFFu; and write wide = (~flags) & kFlagsMask;. The same promotion makes 1 << i land on the sign bit of int even when the caller thinks in bytes.

Assumed widths. int is only guaranteed 16 bits or more; long is 32 bits on Windows (LLP64) and 64 on Linux and macOS (LP64). Java fixes int at 32 bits; Python never wraps. In C and C++ take widths from <cstdint>, counts from CHAR_BIT and std::numeric_limits<T>::digits, and pin them with static_assert(std::numeric_limits<uint32_t>::digits == 32).

Boundary tests, in one table: 0, all-ones (UINT32_MAX), the sign bit (1u << 31), the maximum legal shift (width - 1), the illegal one (width), which must be rejected rather than wrapped, and one negative input to expose sign extension. Build that table under -fsanitize=shift,undefined: the shift hazards are exactly what it is for. In Java the wrapping is defined, so only the tests catch it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Explain endianness: what big- and little-endian disagree about, why shifts and masks are indifferent to byte order but byte-level reads are not, and what breaks when a packed word crosses a machine boundary.

Answer

Endianness is the order in which the bytes of a multi-byte value occupy consecutive memory addresses. Take uint32_t v = 0x12345678 stored at address p:

hostp+0p+1p+2p+3
big-endian0x120x340x560x78
little-endian0x780x560x340x12

Same value, different byte addresses. Big-endian keeps the most significant byte at the lowest address, the order we write hex on paper. Bit numbering is a separate convention: on both families, bit 0 of a byte is the least significant bit. Endianness says nothing about bit order inside a byte, which is why a protocol spec can define "bit 0 of octet 3" and mean the same thing on every machine.

Shifts and masks are value-level operations, so they are endian-agnostic: v >> 16, v & 0xFFu, v | (1u << 7) return the same result everywhere, and the compiler emits whatever instruction the hardware wants. Byte order leaks exactly where memory is involved: pulling a 4-byte field out of a packet buffer, fwrite(&v, 4, 1, f), casting uint8_t* to uint32_t*, dumping a struct. Loading the word out of bytes is the hazard, not the mask applied to it afterwards.

So serialize with explicit shifts, not with the machine's representation. C11:

C
void put_u32_be(uint8_t out[4], uint32_t v) {
    out[0] = (uint8_t)(v >> 24);
    out[1] = (uint8_t)(v >> 16);
    out[2] = (uint8_t)(v >> 8);
    out[3] = (uint8_t)v;
}
uint32_t get_u32_be(const uint8_t in[4]) {
    return ((uint32_t)in[0] << 24) | ((uint32_t)in[1] << 16) |
           ((uint32_t)in[2] << 8)  |  (uint32_t)in[3];
}

The casts matter: in[0] << 24 promotes to int, and shifting 0xFF into the sign bit is undefined behaviour in C. htonl/htons (POSIX) do the same conversion, network byte order is big-endian, but POSIX defines no 64-bit counterpart (glibc and the BSDs ship htobe64/be64toh in <endian.h>), and neither fixes struct layout. Python's int.to_bytes(4, 'big') / int.from_bytes(b, 'big') is the same pair; since Python 3.11 the defaults are byteorder='big'.

Classic bugs:

  • Casting a byte buffer to uint32_t*. A magic number 0x00000102 arrives as 0x02010000 on the other family, and on strict-alignment targets the unaligned pointer is a bus error. memcpy into a uint32_t, then convert.
  • Serializing structs or bit-fields. Bit-field allocation order within a storage unit is implementation-defined (C11 6.7.2.1p11), so struct { uint32_t type:3, len:5; } can emit different bit patterns under different compilers or ABIs. Pack into a uint32_t with shifts, then serialize that integer.
  • Assuming a byte is 8 bits. ISO C only guarantees CHAR_BIT >= 8; POSIX requires 8, and uint8_t exists only if an 8-bit type with no padding exists.

Runtime detection is one line, const uint32_t one = 1; return *(const uint8_t*)&one == 1;, legal only because character types may alias any object. Usually the check is the wrong answer: with shift-based pack/unpack, endianness stops being a variable in the code at all.

Last trap, and it bites in text formats: leading-zero suppression. bin(5) is '0b101': three bits, not eight. Printing a fixed-width field without padding and parsing it back silently changes the width; f"{v:08b}" or to_bytes, whose length is explicit, round-trips. State wire formats in bytes and shifts, "4-byte big-endian unsigned", and never ship a machine representation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Explain XOR from first principles: the truth table, why a ^ a = 0 and a ^ 0 = a, and how those identities power temp-free swaps and the appears-once problems, including where they stop working.

Answer

XOR is addition on each bit position modulo two, with no carry between positions. Bits are computed independently, and everything else falls out of that plus the one-bit truth table.

aba ^ b
000
011
101
110

The output is 1 exactly where the two inputs differ. Read down the table: a ^ a = 0 because identical bits differ nowhere, so every output bit is 0. a ^ 0 = a because zero leaves the other operand's bits untouched. The table is symmetric in a and b, so XOR commutes, and because each bit position is independent, it also associates: a ^ (b ^ c) == (a ^ b) ^ c. So any XOR chain can be reordered and regrouped freely, pairs cancel in any order, and XOR is its own inverse: (a ^ b) ^ b == a.

Paired cancellation, worked:

Python
xs = [2, 3, 5, 3, 2]
acc = 0
for x in xs:
    acc ^= x
# 0^2=2, 2^3=1, 1^5=4, 4^3=7, 7^2=5

The two 2s and the two 3s each cancel to 0, so the survivor is 5 regardless of input order: commutativity and associativity are what make a single O(n) pass, O(1) extra space correct. This is the whole "appears once" problem: the precondition is that every other value appears an even number of times.

Temp-free swap, traced:

Python
a, b = 7, 4
a ^= b   # a = 3   (111 ^ 100)
b ^= a   # b = 7   (100 ^ 011)
a ^= b   # a = 4   (011 ^ 111)

Line 2 restores the original a into b because (a ^ b) ^ b == a; line 3 restores the original b into a. Trap: if both sides name the same variable, the sequence zeroes it. Every line writes the same slot. And in real code a, b = b, a or std::swap is clearer and at least as fast; the XOR swap is interview vocabulary.

Two unpaired elements: XOR the array to get x ^ y. Since x != y that result is nonzero, pick a bit where they differ (the lowest, s = t & -t) and split into elements with s set and without. Each half is the single-number problem again.

Python
t = 1 ^ 2 ^ 1 ^ 3 ^ 2 ^ 5   # = 3 ^ 5 = 6  (0b110)
s = t & -t                  # 0b010
# bit set:   {2, 3, 2} -> 3
# bit clear: {1, 1, 5} -> 5

Where it stops helping:

  • Duplicates that are not paired. [1, 1, 1] and [1] both XOR to 1. If values may repeat three times, XOR is the wrong tool; use per-bit counters modulo three or a hash map. The guarantee you need is "each value appears an even number of times except one", and that belongs in a test.
  • Carries. XOR is addition without carry: 5 ^ 3 = 6 while 5 + 3 = 8. A half adder is sum = a ^ b, carry = a & b, and real addition has to propagate that carry. XOR never stands in for +, and overflow or sign questions are settled by the representation, not by this operator.
  • Language semantics. In Python 3.14 integers are unbounded and ^ behaves as two's complement with an infinite number of sign bits, so negative operands are safe. Fixed-width languages make you reason about the width and the signed range first.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-24

How do you swap two variables in place using bitwise XOR, and what are the edge cases or pitfalls of this technique?

Answer

The 60-second answer. Three XOR assignments, in order, swap two integral values with no temporary:

a ^= b;
b ^= a;
a ^= b;

Each XOR is its own inverse, so the second line recovers the original a and the third recovers the original b. It works for any fixed-width integral type. Say the mechanism, then say you would not ship it: a temporary variable is clearer, and every mainstream compiler already turns t = a; a = b; b = t; into two moves or nothing at all. The trap that actually bites is aliasing, if both operands are the same storage location, the swap silently zeroes it.

Why it works. XOR is associative, commutative, self-inverse (v ^ v == 0) and has 0 as identity. Writing a0, b0 for the originals:

stepexpressionvalue of avalue of b
starta0b0
a ^= ba = a0 ^ b0a0 ^ b0b0
b ^= ab = (a0 ^ b0) ^ b0a0 ^ b0a0
a ^= ba = (a0 ^ b0) ^ a0b0a0

Concrete, with a = 12 (0b1100) and b = 5 (0b0101):

a ^= b   ->  a = 0b1100 ^ 0b0101 = 0b1001  (9)
b ^= a   ->  b = 0b1001 ^ 0b0101 = 0b1100  (12)
a ^= b   ->  a = 0b1001 ^ 0b1100 = 0b0101  (5)

Pitfall 1: aliasing. If both operands are the same object, the first XOR zeroes it and the other two keep it at zero. Guard the pointer case:

C
#include <stdint.h>

void xor_swap(uint32_t *a, uint32_t *b) {
    if (a == b) return;   /* same object: nothing to do */
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

Without the guard, xor_swap(&v, &v) with v == 12:

*a ^= *b   ->  *a = 12 ^ 12 = 0
*b ^= *a   ->  *b = 0 ^ 0 = 0
*a ^= *b   ->  *a = 0 ^ 0 = 0

v is now 0. The same thing happens with arr[i] and arr[j] when i == j: a real bug in naive shuffle code. In languages with value semantics (Python, Java locals) the two operands cannot be the same variable, so this case does not arise.

Pitfall 2: chaining the three assignments into one expression is undefined behaviour. a ^= b ^= a ^= b; modifies a twice with no intervening sequence point (C11 §6.5p2) / unsequenced (C++). GCC and Clang warn under -Wsequence-point and are free to produce anything. Write the three statements separately.

Pitfall 3: types. XOR is defined on integers only. Floating-point needs a bit-cast first (memcpy, or std::bit_cast in C++20), and once you have done that you have gained nothing over a move.

Pitfall 4: it is not faster. The three XORs form a serial dependency chain. Each write feeds the next read. A temporary-variable swap has no such chain: the two moves are independent, and register renaming on an out-of-order core can often eliminate them entirely. GCC and Clang recognise the temp-variable idiom and std::swap; they do not recognise the XOR sequence as a swap. Reaching for the xchg instruction with a memory operand is worse still: it is implicitly locked (Intel SDM), so it serialises the cache line.

When it is useful. Essentially never in application code. It survives as an interview question, as a branchless way to swap two bits or two booleans, and in a few register-starved contexts. If you do use it, guard the aliasing case and keep the three statements on separate lines.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

Given an array where every element appears twice except two elements that appear once, how do you find both of them in O(n) time and O(1) extra space?

Answer

Assume integers, exactly two values appearing once, all others exactly twice, and the two singles distinct. O(1) extra space means excluding the input: no count map, no sorting a copy.

Python
# checked against Python 3.14
def two_singles(a):
    x = 0
    for v in a:
        x ^= v
    if x == 0:
        raise ValueError("premise violated: no two distinct singles")
    lowbit = x & -x          # rightmost bit where the singles differ
    p = q = 0
    for v in a:
        if v & lowbit:
            p ^= v
        else:
            q ^= v
    return p, q

First pass: every paired value cancels against its twin, so x is exactly a ^ b. Since the singles are distinct, x != 0, so at least one bit differs between them. x & -x extracts the lowest such bit: -x is ~x + 1, which leaves the lowest set bit set and flips everything above it, so the AND leaves that single bit. Any differing bit works, 1 << (x.bit_length() - 1) picks the highest instead, but it must be a bit taken from x, not a hard-coded position like bit 0, which fails whenever a and b happen to agree there.

Second pass: a paired value appears twice and both copies have the same v & lowbit, so both land in the same partition and cancel there. The two singles disagree on that bit, so they land in different partitions. XOR each partition and you get both values, in unspecified order.

Worked example with 8-bit values: a = 7 (0b0111), b = 12 (0b1100), paired values 21 and 4. Array [21, 4, 7, 21, 12, 4].

stepaccumulatorvalues XORedresult
first passx21, 4, 7, 21, 12, 47 ^ 12 = 11 (0b1011)
isolate bit—11 & -111 (bit 0)
bit 0 setp21, 21, 77
bit 0 clearq4, 4, 1212

One XOR accumulator cannot finish this: from x = 11 alone you cannot tell (7, 12) from (3, 8) or (1, 10), because a ^ b is symmetric and throws away which value is which. The partition supplies a second independent equation over GF(2) that breaks that symmetry, which is exactly why the two-single version needs two passes while the one-unpaired version needs one, and the survivor of that single XOR is already the answer.

Traps: x == 0 means the two singles are equal or the input is malformed, so that branch is not decorative. Python handles negative values here because its ints are arbitrary precision and -x is well defined; in 32-bit signed C, x & -x is undefined behaviour when x is INT_MIN, so compute the mask in an unsigned type or shift within a known width. Post-checks are cheap: p ^ q == x and p != q. A hash map of counts is also O(n) time but O(n) space; sorting costs O(n log n) and mutates or copies the input.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How does Brian Kernighan's algorithm count set bits, and how does its time complexity compare to iterating through the word length?

Answer

Kernighan's algorithm counts set bits by clearing the lowest set bit on every pass: n &= n - 1. Each pass removes exactly one 1, so the loop runs k times where k = popcount(n). That is O(k) instead of the O(W) you pay for testing all W bit positions of the word. For a 64-bit word holding 3 set bits, that is 3 iterations instead of 64.

Why n & (n - 1) clears the lowest set bit

Subtracting 1 from a non-zero n flips the lowest set bit from 1 to 0 and turns every trailing 0 below it into 1. Bits above the lowest set bit are untouched. AND-ing the two values keeps those high bits and zeroes the whole low run, because the flipped bit is 0 in n - 1 and the trailing ones are 0 in n:

n        = 0b00101100   (44)
n - 1    = 0b00101011   (43)
n & (n-1)= 0b00101000   (40)   <- bit 2 cleared, bits 3 and 5 kept

Trace for n = 44

Iterationn beforen - 1n aftercount
144 0b0010110043 0b0010101140 0b001010001
240 0b0010100039 0b0010011132 0b001000002
332 0b0010000031 0b000111110 0b000000003

Three iterations for three set bits, then the loop exits on n == 0.

Python
# Python 3.8+
def count_set_bits(n: int) -> int:
    count = 0
    while n > 0:          # n == 0 exits immediately; negatives never enter
        n &= n - 1
        count += 1
    return count

On Python 3.10 or newer, n.bit_count() is the intrinsic and is what you should actually ship; the loop above is the thing to be able to write on a whiteboard.

Cost comparison

MethodIterationsNotes
KernighankLoop-carried dependency: each n depends on the previous, so ~2 cycles per iteration on a modern core
Shift-and-testWIndependent iterations, unrolls and pipelines well
Byte lookup tableW/8256-entry table, 8 dependent loads for a 64-bit word
POPCNT (x86, SSE4.2)13-cycle latency, 1/cycle throughput on Skylake

For a 64-bit word with k = 64, Kernighan's loop is ~64 dependent iterations, roughly 128 cycles by the estimate above, against 3 cycles for POPCNT. The crossover is real: Kernighan wins only when k is small.

Failure modes

  • Negative and arbitrary-precision inputs. In Python, -1 & -2 == -2, -2 & -3 == -4, and the magnitude keeps growing, so a while n: loop never terminates. The while n > 0 guard above sidesteps it by returning 0 for negatives, which is usually not what the caller wanted. (-1).bit_count() returns 1, because Python defines it over the absolute value.
  • Signed types in C/C++. With while (n) and a negative int, the loop never reaches 0 and eventually overflows INT_MIN - 1, which is undefined behaviour. With while (n > 0) it silently returns 0. Cast to uint32_t/uint64_t at the call boundary and assert n >= 0 on the way in.
  • Dense words. When k approaches W there is no work saved, and the trip count varies per call, so the loop-exit branch mispredicts roughly once per invocation on random data. Test with 0, -1, INT_MIN, and all-ones; a hang on -1 is the sign-extension bug, not a slow machine.

Use Kernighan when the input is sparse and you cannot rely on a popcount instruction: bitmask adjacency sets, sparse Bloom filters, embedded targets without SSE4.2. Otherwise call POPCNT, __builtin_popcount, or Integer.bitCount(), all of which lower to it.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-17

Walk me through counting the set bits of an integer: the naive loop, the n & (n - 1) trick with one worked example, why it runs in O(number of set bits), and what breaks at n = 0 and for negative values.

Answer

Two loops, and the difference between them is one line.

C
#include <stdint.h>

int popcount_naive(uint32_t n) {
    int c = 0;
    for (int i = 0; i < 32; ++i) c += (n >> i) & 1u;   /* always 32 iterations */
    return c;
}

int popcount(uint32_t n) {
    int c = 0;
    while (n) { n &= n - 1u; ++c; }                    /* one iteration per set bit */
    return c;
}

The second works because n - 1 does two things at once: it turns off the lowest set bit and turns on every bit below it. AND-ing back therefore removes exactly that one bit and leaves everything above it untouched. The invariant is "c plus the set bits still in n equals the original count"; each iteration removes exactly one bit, so the loop runs exactly popcount(n) times and exits when n reaches 0.

Worked on 180 = 0b10110100 (8-bit unsigned):

stepnn - 1n & (n - 1)c
01011010010110011101100001
11011000010101111101000002
21010000010011111100000003
31000000001111111000000004

Four set bits, four iterations. The naive loop takes 8 for this value and also 8 for the value 1; Kernighan takes 4 for 180 and 1 for 1. So the honest statement is O(w) versus O(popcount(n)), and the worst case is identical, because an all-ones word costs w iterations either way. Kernighan is not asymptotically better in general. It is better exactly where words are sparse, which is the case you usually have.

The same subtraction gives the power-of-two test:

C
int is_pow2(uint32_t n) { return n != 0 && (n & (n - 1u)) == 0; }

A power of two has exactly one set bit, and clearing it must yield zero. n = 0 is the whole reason for the guard: 0 minus 1 wraps to all ones in unsigned, so 0 & (0u - 1u) == 0, and a test without the n != 0 happily calls zero a power of two. On the signed version the guard should be n > 0, which also excludes INT_MIN: its two's-complement pattern has one set bit, but the value is not a power of two.

Negatives are where "how many bits are set in the representation" and "how many bits are set in the magnitude" come apart. The function above counts the 32-bit pattern, so (uint32_t)-1 gives 32. Python's int.bit_count() counts ones in the absolute value instead: (-5).bit_count() is 2, not 30 (added in 3.10, per the Python 3.14 docs). Pick one meaning, say so in the name or the signature, and take the parameter as unsigned so callers have to decide.

The failure I'd expect in review: a signed parameter with the shifting variant. With an arithmetic right shift, -1 >> 1 is still -1, so while (n) { c += n & 1; n >>= 1; } never terminates. It survives testing because every test input happens to be non-negative.

In production I call the language's popcount and use the Kernighan loop only when I want to visit the set bits anyway, or when the word is wide and sparse. The loop earns its place when you need the bits, not just their count.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach clearing the lowest set bit to an engineer who has only seen it as a rule of thumb.

Answer

The operation. For a fixed-width unsigned integer x, x & (x - 1) clears the lowest set bit and leaves every other bit unchanged.

Why it works. Write the lowest set bit as position k. By definition every bit below k is 0. Subtracting 1 from x borrows from bit k: bit k flips to 0, and every bit below it flips to 1. Bits above k are untouched. So x - 1 has a 0 at position k, 1s at every position below k, and the same bits above. AND with x: position k is 0 & 1 = 0, positions below are 0 & 1 = 0, positions above are unchanged. The lowest set bit is gone; nothing else moved.

Trace with x = 44 = 0b101100:

  • lowest set bit is bit 2 (value 4)
  • x - 1 = 43 = 0b101011
  • x & (x - 1) = 0b101000 = 40

40 = 44 - 4. Exactly the lowest set bit removed.

The companion. x & -x isolates that same bit. In two's complement, -x = ~x + 1, which flips everything above the lowest set bit and leaves the bit itself set. AND with x keeps only that bit. For x = 44, x & -x gives 4. Useful for iterating set bits or for Fenwick trees.

Kernighan's algorithm. Clearing one bit per iteration means the loop runs popcount(x) times, not width times:

Python
def popcount(x: int) -> int:
    n = 0
    while x:
        x &= x - 1
        n += 1
    return n

For x = 44 = 0b101100: 44 → 40 → 32 → 0, three iterations, popcount 3. A naive loop over all 32 bits would run 32 times.

Failure modes.

  1. Negative values. In two's complement, x & (x - 1) still clears the lowest set bit, but the sign bit stays set, so x never reaches 0 and the loop never terminates. Guard with if x < 0: raise or work on a fixed-width unsigned view. Python's arbitrary-precision ints make this worse: -1 & -2 == -2, so the loop spins forever.
  2. Assuming it beats hardware. x86-64 has POPCNT (SSE4.2, 2008) and ARM has CNT; both compute popcount in a single instruction with a few cycles of latency. Kernighan's loop is O(popcount) iterations of a few instructions each, so it only wins when the value is very sparse and no hardware instruction is available. Measure, don't assume.
  3. x = 0. x - 1 = -1, x & (x - 1) = 0. The loop body never runs; popcount 0 is correct. No special case needed.

When to use. Use int.bit_count() (Python 3.10+) or the hardware instruction when you want popcount. Reach for x & (x - 1) when you want to iterate set bits, clear the lowest one, or test whether a value is a power of two (x & (x - 1) == 0 for x > 0).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How do you isolate the lowest set bit of an integer using two's complement operations, and why does x & (-x) work?

Answer

To isolate the lowest (least significant) set bit of an integer x, evaluate x & (-x) (or x & (~x + 1)).

The Mechanism

In two's complement representation, negating a number is defined as bitwise NOT followed by adding 1: -x = ~x + 1.

Any non-zero integer x can be written in binary as:

x = [prefix] 1 [trailing zeros]

where [prefix] is an arbitrary sequence of bits, 1 is the lowest set bit at position $k$, and [trailing zeros] is a sequence of $k$ zero bits.

Now trace what happens during -x:

  1. Bitwise NOT flips every bit:
    ~x = [~prefix] 0 [trailing ones]
    The lowest set bit becomes 0, and the $k$ trailing zeros become $k$ trailing ones.
  2. Adding 1 ripples a carry through those trailing ones:
    -x = ~x + 1 = [~prefix] 1 [trailing zeros]
    The addition turns the $k$ trailing ones back to $0$ and adds $1$ to position $k$, turning its 0 back into 1. The carry stops at position $k$ and does not propagate into [~prefix].

Now, bitwise AND x with -x:

  • At bits above position $k$: [prefix] & [~prefix] = 0 (since $b & \neg b = 0$).
  • At position $k$: 1 & 1 = 1.
  • At bits below position $k$: 0 & 0 = 0.

The result preserves only the single bit at position $k$, clearing all others.

Concrete 8-bit Example

Let x = 44 (0010 1100 in binary):

ExpressionBinary ValueDecimal / Description
x0010 110044 (lowest set bit is bit 2, value 4)
~x1101 0011Bitwise NOT
-x (~x + 1)1101 0100-44 (carry flips trailing ones to 0, sets bit 2)
x & (-x)0000 01004 (isolated bit 2)

Edge Cases and Failure Modes

  1. x = 0: 0 & (-0) = 0 & 0 = 0. Returns 0 safely without conditional branches.
  2. x = INT_MIN in signed two's complement (e.g., -2147483648 in 32-bit): Signed negation -INT_MIN overflows because the range is asymmetric ($[-2^{w-1}, 2^{w-1}-1]$). In C and C++, signed integer overflow is undefined behavior (UB). In Java or Python (with fixed-width emulation) or modular unsigned types (uint32_t), -INT_MIN wraps around to INT_MIN (0x80000000). Since INT_MIN has only its sign bit set, 0x80000000 & 0x80000000 = 0x80000000. To make this safe in C/C++, cast to an unsigned type first:
    C
    uint32_t isolate_lsb(uint32_t x) {
        return x & (~x + 1u); /* or x & -x on unsigned types */
    }
  3. Modern Hardware / Builtins: On modern x86 with BMI1, x & (-x) compiles directly to the BLSI instruction (blsi eax, ecx), executing in 1 cycle. In C/C++, GCC and Clang provide __builtin_ctz(x) to find the index directly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does isolating the lowest set bit matter, and where is it irrelevant?

Answer

The 90-second answer. x & -x produces a one-hot mask of the lowest set bit: a value with exactly one bit set, at the position of the least significant 1 in x. It matters wherever you need to walk or index set bits without scanning zeros: Fenwick trees, bitset iteration, hardware priority encoders. It is irrelevant when what you actually need is the index (a trailing-zero count gives that in one instruction), when you need the highest set bit, or when you are not doing bit-parallel work at all.

Why it works. In two's complement, -x = ~x + 1. Adding 1 to ~x carries up through every bit from the lowest set bit of x upward until the carry stops at that bit; everything below stays 0. So -x agrees with x only at the lowest set bit, and x & -x keeps exactly that bit.

Where it earns its place. The Fenwick tree (binary indexed tree) is the canonical case: its index arithmetic is entirely lowbit:

Python
def update(tree, i, delta):        # 1-based i
    while i < len(tree):
        tree[i] += delta
        i += i & -i

def prefix(tree, i):
    s = 0
    while i > 0:
        s += tree[i]
        i -= i & -i
    return s

Trace update(tree, 5, d) on a tree of size 8: i=5, 5 & -5 = 1 → i=6; 6 & -6 = 2 → i=8; 8 & -8 = 8 → i=16, stop. Touches 5, 6, 8: three nodes, O(log n). Trace prefix(tree, 7): i=7, lowbit 1 → 6; lowbit 2 → 4; lowbit 4 → 0. Sums tree[7] + tree[6] + tree[4]. Both paths are O(log n) because each step strips one bit.

Second case: iterating only the set bits of a word, O(popcount) instead of O(width).

Python
x = 0b101100
while x:
    low = x & -x
    print(low.bit_length() - 1)
    x ^= low
# prints 2, 3, 5

Trace: 44 & -44 = 4 → index 2; 40 & -40 = 8 → index 3; 32 & -32 = 32 → index 5; then 0. Three iterations for three set bits.

Where it is irrelevant.

You wantx & -xUse instead
index of lowest set bitmask onlyctz/tzcnt, Integer.numberOfTrailingZeros, (x & -x).bit_length()-1
highest set bitwrong bitx.bit_length()-1, clz
clear lowest set bitwrongx & (x-1)
membership in a small setoverkilla hash set

If the platform has a trailing-zero intrinsic, x & -x is a redundant extra op: tzcnt is one instruction and yields the index directly. And if you are storing a handful of integers, a set is clearer and fast enough; the trick only pays when you are processing words in parallel.

Failure modes.

  • x = 0: 0 & -0 == 0, no bit isolated. A while x: loop is safe; (x & -x).bit_length() - 1 silently returns -1.
  • Signed overflow in C: -INT_MIN is undefined behaviour. Use unsigned for the operand.
  • Python's unbounded ints: x & -x is correct for positive x, but -5 & 5 == 1. The mask describes 5, not -5. Do not reason about a sign bit that does not exist.
  • Confusing mask with index: the result is a power of two, not a position. Off-by-one if you forget the -1.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How do you check whether a given 32-bit integer is a power of four using bit manipulation?

Answer

What to say first. Clarify two things before writing code: is n signed or unsigned, and is k = 0 allowed (i.e. is 1 a valid answer)? Then state the rule: a power of four is a power of two whose single set bit sits at an even index. That gives three tests: positive, exactly one bit set, that bit in an even position.

C
// C11, 32-bit. uint32_t avoids signed-overflow UB in n - 1.
#include <stdbool.h>
#include <stdint.h>

bool is_power_of_four(uint32_t n) {
    return n != 0
        && (n & (n - 1)) == 0        // exactly one bit set
        && (n & 0x55555555u) != 0;   // that bit is at an even index
}
Python
# Python 3, arbitrary-precision ints
def is_power_of_four(n: int) -> bool:
    return n > 0 and (n & (n - 1)) == 0 and (n & 0x55555555) != 0

Why each test. n & (n - 1) clears the lowest set bit; it is zero only when exactly one bit was set, i.e. n = 2^j. The mask 0x55555555 is 0101...0101: bits 0, 2, 4, …, 30 set, every odd index clear. Since the power-of-two test already guarantees a single bit, n & mask is either n (even index, so n = 4^k) or 0 (odd index, so n = 2^(2k+1)). That is why != 0 and == n are interchangeable here, and why the equivalent form (n & 0xAAAAAAAA) == 0 also works. For 64-bit inputs the constant becomes 0x5555555555555555.

Trace.

nset bitn & (n-1)n & 0x55555555result
1 = 4⁰01 & 0 = 01true
4 = 4¹24 & 3 = 04true
64 = 4³664 & 63 = 064true
2³⁰ = 10737418243002³⁰true
212 & 1 = 00false
838 & 7 = 00false
2³¹ = 21474836483100 (bit 31 clear in mask)false
0—0 & -1 = 0—false
-214748364831——false

Alternative: modulo 3. 4^k = (3+1)^k ≡ 1 (mod 3), while 2^(2k+1) = 2·4^k ≡ 2 (mod 3). So n > 0 && (n & (n-1)) == 0 && n % 3 == 1 is also correct. Both are O(1); the mask version is one AND, whereas n % 3 with a constant divisor compiles to a multiply-shift sequence (gcc emits imul plus shifts, not a div). The instruction-count difference is real but unmeasurable next to the branch: pick whichever reads better in the codebase.

Failure modes.

  • Zero. 0 & -1 == 0, so the power-of-two test passes for 0. The n > 0 guard is not optional.
  • INT_MIN in fixed-width languages. 0x80000000 & 0x7FFFFFFF == 0, so -2³¹ passes the power-of-two test. In Java and C# the subtraction wraps by definition and you get a false positive; in C/C++ INT_MIN - 1 is signed overflow and therefore undefined behaviour, so the expression is not merely wrong, it is unportable. Using uint32_t (or the n > 0 guard) removes the whole class.
  • Arbitrary-precision integers. Python and Ruby have no 32-bit truncation: a negative n has infinitely many leading 1 bits, so n & (n - 1) is generally nonzero and the mask test is meaningless. The n > 0 guard is what makes the snippet correct there.
  • Wrong width. Applying the 32-bit mask to a 64-bit value silently rejects 4^16 and above; use the 64-bit constant.

Complexity is O(1) time and O(1) space: three comparisons and two bitwise ops, no loops.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Given an integer mask with k set bits, how do you enumerate all 2^k of its subsets, and what is the total cost when you run that loop for every mask of an n-bit universe?

Answer

Enumerating the 2^k submasks of mask is one loop. The endpoints are where it goes wrong.

Python
# Python 3.11
def submasks(mask):
    s = mask
    while True:
        yield s
        if s == 0:
            break
        s = (s - 1) & mask

For mask = 0b1010 (k = 2) that yields 1010, 1000, 0010, 0000: four values, 2^2, each exactly once.

The mechanism: s - 1 clears the lowest set bit of s and sets every bit below it; & mask throws away anything outside the mask. What survives is the largest submask strictly smaller than s, so the loop walks submasks in decreasing value and lands on 0 last. 0 is a submask, the empty set, so the termination test belongs after the visit. for (int s = mask; s; s = (s - 1) & mask) in C++ never reaches the body with s == 0, so it silently drops the empty subset. A do-while that advances before visiting drops mask instead, and with a signed int it can spin forever: (0 - 1) & mask == mask, so the walk restarts at the top. This is exactly the family of loops to write with unsigned and to test with mask = 0, mask = 1 and a full mask.

Cost: 2^k visits at O(1) each, and k is the number of set bits, not the word width. A mask with three set bits costs eight iterations regardless of how wide the integer is. Summed over all 2^n masks of an n-bit universe the total is exactly 3^n, because each bit has three states: outside the mask, in the mask but outside the submask, or in both. So Σ_k C(n,k)·2^k = 3^n.

n2^n masks3^n submasks visited
1532,76814,348,907
201,048,5763,486,784,401
224,194,30431,381,059,609

Roughly 10^9 simple iterations per core-second, so n = 15 is comfortable and n = 20 is where I check the recurrence before writing this loop at all.

Supersets go upward: s = (s + 1) | mask, bounded by the universe.

Python
U = (1 << n) - 1
s = mask
while s <= U:
    visit(s)
    s = (s + 1) | mask

For mask = 0b0010, n = 4: 0010, 0011, 0110, 0111, 1010, 1011, 1110, 1111. Eight values, 2^3. For descending supersets I go through the complement: walk submasks of free = U ^ mask and OR mask back in. Note the shape of the stop condition: with U = (1 << n) - 1 you compare against U, not against 1 << n, or you visit a value with a bit outside the universe.

Where this earns its keep is subset DP: any recurrence that partitions a set:

Python
INF = float('inf')
best = [INF] * (1 << n)
best[0] = 0
for mask in range(1, 1 << n):
    sub = mask
    while sub:
        best[mask] = min(best[mask], cost[sub] + best[mask ^ sub])
        sub = (sub - 1) & mask

That is 3^n work total for n items, so it is a real algorithm up to about n = 20. For min, max, and and or, seeing each partition twice (sub and mask ^ sub) is harmless; for a sum it double counts, so pin one element (lsb = mask & -mask, skip any sub without it) which also halves the work.

When not to use it: if the recurrence is a sum over submasks rather than a partition ("for each mask, sum f over its submasks", the zeta transform), the fast zeta/SOS transform does the same thing in n·2^n and beats 3^n outright. And past roughly k = 25 the state space is the problem, not the enumeration; no loop shape rescues it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How do you represent subsets using bitmasks in dynamic programming, and how do you iterate through all submasks of every mask in O(3^n) time?

Answer

An integer acts as a compact bitmask representing a subset of an $n$-element universe ($U = {0, 1, \dots, n-1}$). If bit $i$ is set ((mask >> i) & 1 == 1), element $i$ belongs to the subset. Dynamic programming states map directly to array indices from $0$ to $2^n - 1$, providing $O(1)$ set membership, union (mask_a | mask_b), intersection (mask_a & mask_b), and complementation ((~mask) & ((1 << n) - 1)).

When transitions require partitioning a mask into two disjoint subsets or enumerating all submasks (for instance, in the optimal subset-sum partitioning or chromatic number problems), iterating through all $2^n$ integers for each mask takes $O(4^n)$ time. Instead, we can enumerate strictly the valid submasks of a given mask using bitwise subtraction.

The Submask Enumeration Idiom

C++
for (int mask = 0; mask < (1 << n); ++mask) {
    // sub starts at mask, decrements, and masks back to mask
    for (int sub = mask; sub > 0; sub = (sub - 1) & mask) {
        // Process non-empty submask 'sub' of 'mask'
    }
    // Handle sub = 0 separately if needed
}

Mechanism of (sub - 1) & mask

Subtracting 1 from sub flips the least significant set bit of sub to 0 and sets all lower bits to 1. Bitwise-ANDing the result with mask clears any newly turned-on bits that were not present in mask, while preserving valid bits from mask below that position. This directly yields the next lexicographically smaller submask in strictly decreasing order without visiting any non-subset values.

Trace for mask = 0b1010 (elements {1, 3})

  1. sub = 0b1010 (10)
  2. sub - 1 = 0b1001 (9); 9 & 10 = 0b1000 (8)
  3. sub - 1 = 0b0111 (7); 7 & 10 = 0b0010 (2)
  4. sub - 1 = 0b0001 (1); 1 & 10 = 0b0000 (0) -> loop terminates.

Visited submasks: 0b1010 ({1, 3}), 0b1000 ({3}), 0b0010 ({1}), plus 0b0000 ($\emptyset$) when accounted for.

Complexity Proof: $O(3^n)$

A mask with $k$ set bits has exactly $2^k$ submasks. Summing across all masks of size $n$ by grouping by the number of set bits $k$:

$$\sum_{k=0}^{n} \binom{n}{k} 2^k \cdot 1^{n-k} = (2 + 1)^n = 3^n$$

Combinatorially, every element in $U$ has three mutually exclusive states: it is absent from mask, present in mask but absent from sub, or present in both mask and sub. Thus, iterating all pairs (mask, sub) across the entire space takes exactly $3^n$ iterations, compared to $4^n$ for naive iteration. For $n = 15$, $3^{15} \approx 1.43 \times 10^7$ operations (well within a 1-second budget), whereas $4^{15} \approx 1.07 \times 10^9$ will time out.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does bitmasks as sets change if the workload grows by two orders of magnitude?

Answer

Core answer

A bitmask's guarantee is narrow: union, intersection and difference are one instruction only while the universe fits a machine word. 64 elements on x86-64. Grow the workload 100x and you cross that line, and the cost model shifts from "count instructions" to "count cache misses and bytes moved." Two things grow independently: the universe per set, and the number of sets.

If the universe grows 100x (say 64 → 6,400 elements), a single word becomes a 100-word bitset. Set ops stay word-parallel but are now O(U/64) instead of O(1): 100 word-ORs, or 25 with AVX2. Still cheap. If the number of sets grows 100x, memory grows 100x, and that is usually what bites first.

Mechanism and arithmetic

Take a 1,000,000-element universe.

  • Bitset: 1,000,000 bits = 125 KB. Union = 15,625 uint64 ORs. Working set for dst = a | b is 375 KB, which fits L2 (1–2 MB on a server core), so it streams at memory bandwidth: order 10 µs.
  • Hash set: ~32 bytes/entry → ~32 MB for a full set. Union iterates and hashes every element; each probe is a likely cache miss at ~100 ns → order 50–100 ms.

That is a ~5,000x gap, and it widens with scale: the bitset's per-element cost falls as 1/64 (amortized word op), while the hash set's stays constant. Word-parallelism is a fixed 64x multiplier: it does not grow with the workload, but the hash set's pointer-chasing penalty does.

Memory crossover: bitset = U/8 bytes; hash set ≈ 32·|S| bytes. Equal at |S| = U/256: density 0.4%. Above that the bitset is smaller; below it, a 125 KB bitset holding three elements is waste.

Code (word-level, C)

C
#include <stdint.h>
#define NWORDS 15625            // 1,000,000 / 64
void set_union(uint64_t *dst, const uint64_t *a, const uint64_t *b) {
    for (int i = 0; i < NWORDS; i++)
        dst[i] = a[i] | b[i];   // 1 load a, 1 load b, 1 OR, 1 store per word
}

15,625 iterations; auto-vectorized to AVX2 that is ~3,900 instructions. In Python the same expression is a big-int op that is not one instruction: CPython loops over 30-bit digits, so a 1M-bit mask is ~33,000 digit ops per union. The single-instruction claim is a C/word-level claim, not a Python one.

Trade-offs

RepresentationMemory (U=1M)UnionIterate membersWins when
Single-word bitmask8 B1 instructionbit tricksU ≤ 64
Multi-word bitset125 KB~15,625 word opsO(U/64) scandense, set-algebra heavy
Hash set~32 MBO(|A|+|B|) hashesO(|S|)sparse, membership-heavy
Roaring bitmap~KB–MBmergeO(|S|)mixed density

A bitmask still wins at scale when the universe is dense and the workload is set algebra: many unions/intersections, membership tests, subset DP. It loses when sets are sparse (iteration scans the whole universe) or when you need to enumerate members cheaply.

Failure modes

  • Silent blowup: 100x more sets × 125 KB each = 12.5 GB for 100,000 sets. Detect by tracking total bitset bytes, not per-set size.
  • Sparse bitsets: a 1M-bit mask holding 50 elements makes every intersection scan 15,625 words to touch 50 bits. Detect by logging density = |S|/U; below ~0.4% switch to a hash set or roaring.
  • Python big-int assumption: code that "works" at 64 elements silently becomes O(U/64) per op at 1M. Detect by profiling op cost against universe size.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of iterating set bits?

Answer

The short answer

Refuse when the design's complexity claim is O(set bits) but the workload makes set bits Θ(word width), and refuse when the loop enumerates bits to answer a question that is a predicate or a count. Both are cost-model errors, not style preferences.

What the loop actually costs

Isolate-and-clear visits each set bit once:

Python
# Python 3
x = 0b10110100  # 180
while x:
    bit = x & -x          # lowest set bit
    i = bit.bit_length() - 1
    process(i)
    x ^= bit              # clear it

Trace: x=180 → bit=4, i=2, x=176; bit=16, i=4, x=160; bit=32, i=5, x=128; bit=128, i=7, x=0. Four iterations for four set bits. On a 64-bit word with 3 bits set it is 3 iterations, not 64.

That is the whole guarantee: iterations = popcount. It says nothing about how large popcount is.

Where the design breaks

SituationCost of isolate-and-clearWhat to do instead
Sparse mask, k ≪ widthO(k)keep it
Dense mask, k ≈ widthO(width), same as a scan, worse constantsfull scan, or drop the bitset
"Is any bit set?"O(k) wastedx != 0
"How many bits set?"O(k)x.bit_count() (Python 3.10+), or hardware POPCNT
"Is bit i set?"O(k) to reach it(x >> i) & 1

The refusal cases:

  1. The sparsity assumption is unstated and false. A bitmap index, a Bloom filter near saturation, or a bitset of "all IDs in this range" all drift toward dense. If the design says "we iterate only the set bits, so it's cheap" and nothing bounds the fill ratio, the capacity plan is wrong. A 4096-bit bitset at 50% fill is 2048 iterations versus 4096 for a scan: a 2× win sold as an asymptotic one.

  2. Width is attacker- or tenant-controlled. A per-packet or per-request loop whose worst case is the mask width turns a dense input into a latency spike. If the mask comes from outside, the worst case is the design's worst case.

  3. Enumeration is unnecessary. Iterating set bits to count them, to test emptiness, or to test one bit is a design smell: the loop does O(width) work to answer an O(1) question.

  4. The bitset is the wrong structure. If you iterate a dense mask to recover a list of elements, you have built a slow array. Use the list.

When it is the right call

Sparse masks with a bounded, known fill ratio (routing tables, sparse adjacency, feature flags where a handful of bits are set) are exactly what the loop is for. The condition to write into the design is the bound on popcount, not the loop itself.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Why do hash functions include a bit-mixing or avalanche step, and how would you recognize a weak mixer: in the code, and in a measurement?

Answer

A mixing step exists to destroy the structure of real keys before the table picks off a handful of bits of the hash. A 2^16-slot open-addressing table indexes with h & 0xFFFF, sixteen bits, and anything those bits inherit from the key becomes clustering.

Raw integer hashing is exactly where the structure leaks. Take the Fibonacci form h(x) = x * 2654435761u (mod 2^32), where 2654435761 is 0x9E3779B9 ≈ 2^32/φ. Bit j of a product depends only on input bits 0..j, because carries travel upward. Flip input bit 31 and the product moves by 2^31 × C ≡ 2^31 (mod 2^32) since C is odd: the output differs by exactly 0x80000000, i.e. one output bit flips out of 32. Average over all input bits and it can look respectable; open the per-bit table and it is a disaster. h(x) = x % m has the same disease with sequential ids: consecutive keys land in consecutive slots, and linear probing turns that into primary clustering that degrades badly as load factor rises.

The criterion is avalanche, usually called the strict avalanche criterion: for every pair of inputs differing in exactly one bit, each output bit should flip with probability 1/2. So one input bit should flip ~16 of 32 output bits, with standard deviation 2.83 on a single test. Any input-bit/output-bit pair that always or never flips is a weak mixer, even if the row averages look fine.

Concrete mixers a candidate should be able to write from memory:

namebodynotes
Fibonacci / multiply-shiftidx = (x * 2654435761u) >> (32 - k)0x9E3779B9 ≈ 2^32/φ; 64-bit constant 11400714819323198485 ≈ 2^64/φ; take the high bits
murmur3 fmix32h ^= h>>16; h *= 0x85ebca6b; h ^= h>>13; h *= 0xc2b2ae35; h ^= h>>1632-bit finalizer
murmur3 fmix64h ^= h>>33; h *= 0xff51afd7ed558ccd; h ^= h>>33; h *= 0xc4ceb9fe1a85ec53; h ^= h>>3364-bit finalizer

Notice the shape: shift-xor, multiply, shift-xor, multiply. The shift-xor stages on their own are GF(2)-linear, h(x ^ y) == h(x) ^ h(y), so the output difference depends only on the input difference and never on the values. Every differential test then gives the same answer, the map is a linear matrix an attacker can invert by back-substitution, and a x ^ (x>>1) ^ (x>>3) style "mixer" is reversible in a few lines. The multiply is the only nonlinearity in these finalizers: carries break XOR's linearity. Interleaving the two is the whole trick.

The measurement is small enough to paste into an interview:

C
/* C11, checked with gcc -std=c11 */
#include <stdint.h>
#include <stdio.h>

static uint32_t fmix32(uint32_t h) {
    h ^= h >> 16; h *= 0x85ebca6bu;
    h ^= h >> 13; h *= 0xc2b2ae35u;
    h ^= h >> 16; return h;
}

int main(void) {
    uint64_t row[32] = {0};                 /* row[i]: flips caused by input bit i */
    uint32_t s = 1u;
    for (int n = 0; n < 100000; ++n) {
        s = s * 1664525u + 1013904223u;     /* cheap key stream */
        for (int i = 0; i < 32; ++i) {
            uint32_t d = fmix32(s) ^ fmix32(s ^ (1u << i));
            row[i] += (uint32_t)__builtin_popcount(d);
        }
    }
    for (int i = 0; i < 32; ++i)
        printf("%2d %.3f\n", i, (double)row[i] / 100000.0);
}

Every row prints 16.000 ± 0.01 for fmix32 (standard error 2.83/√100000 ≈ 0.009). Swap in x * 2654435761u as the candidate and row 31 prints exactly 1.000. That single row is the difference between a finalizer and a constant.

What I do in practice: run the same sweep on the real key distribution (record ids, timestamps, bitmaps), not just random words, and inspect the full 32×32 matrix of per-cell flip rates rather than row sums. A lumpy matrix with columns of 0s and 1s is a mixer that will show up as probe-length variance later. Two traps worth naming: judging a mixer by collision counts on one dataset, which hides structure until the table is full; and treating an avalanche finalizer as security. fmix32 diffuses; it is not one-way, and no amount of avalanche gives you preimage resistance.

Curated: · Written: · Reviewed:

Difficulty: Hard