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.

Overview

Curated: · Written: · Reviewed:

Bit Manipulation

In one line

Working on an integer's binary digits with AND, OR, XOR, NOT and shifts, inside a fixed width, to test, set, clear or isolate bits, enumerate subsets, or pack fields in constant time. Reach for it when bits are the domain model (flags, protocol fields, sets over a universe no wider than the word) or when an identity such as x & (x - 1) gives the answer directly. It is not a general speed-up.

Key definitions

  • Two's complement: signed encoding where the top bit has weight -2^(w-1). -x equals ~x + 1.
  • Arithmetic vs logical shift: >> on a signed value replicates the sign bit and rounds toward negative infinity. Unsigned types, and Java's >>>, fill with zeros.
  • Lowest set bit: x & -x. Clear it with x & (x - 1).
  • Submask: s is a submask of m when s & m == s. Enumerate with sub = (sub - 1) & m.
  • Width: the bit count the type guarantees. Shifts at or above it are undefined in C, masked to the low 5 bits in Java, and unbounded in Python.

Formulas and complexity

−x=∼x+1x & (−x)=lowest set bit-x = \sim x + 1 \qquad x \,\&\, (-x) = \text{lowest set bit} ∑m=02n−12∣m∣=3n(submask pairs over all masks)\sum_{m=0}^{2^n-1} 2^{\lvert m \rvert} = 3^n \quad \text{(submask pairs over all masks)} Held-Karp table bytes=2n⋅n⋅8\text{Held-Karp table bytes} = 2^n \cdot n \cdot 8
  • Kernighan popcount: O(number of set bits), not O(width).
  • Iterate set bits with isolate and clear: one step per set bit.
  • XOR pairing: O(n) time, O(1) extra space.

How it works

  • An integer of width w is a vector of w booleans. Test with x & (1 << i) and compare to zero. Set with |=, clear with &= ~(1 << i), toggle with ^=.
  • Subtracting one flips the trailing zeros and the lowest set bit, so x & (x - 1) clears exactly the lowest set bit. Example: 0b10110100 & -0b10110100 is 0b100.
  • x ^ x = 0 and x ^ 0 = x, so a XOR over a list that pairs every value cancels the pairs and leaves the unpaired one.
  • With two unpaired values p and q, x = p ^ q is nonzero. Any set bit of x separates p from q, so XOR each group to recover them.

When to use and when not to

SituationUse bitsUse something else
Flags, permissions, feature setsyes
Dense set over a universe of at most 64 elementsyes, union and intersection in one instructionbitset library or hash set beyond the word
Dense membership over 10,000,000 idsbitset, 1.25 MBhash set when sparse
Subset DPup to about n = 20larger n: 2^n x n table outgrows memory
Replacing n // 2 with n >> 1nocompiler already emits the shift for unsigned values; differs for negatives
Packing a network fieldyesexplicit byte order at the boundary

Traps interviewers probe

  • Dividing a signed value with a shift. -25 >> 3 is -4, while -25 / 8 truncates to -3. Fix: use division when the rounding direction matters.
  • Shift counts at the width. Java 7 << 32 is 7 because the count is masked to 0, so (shardId << 32) | sequence drops the shard. Fix: widen to long before shifting, and keep counts below the width.
  • Toggling where you mean to set or clear. state ^= 1 << 5 flips the bit, so resuming an unpaused job pauses it. Fix: state &= ~(1 << 5) to clear, |= to set.
  • Renumbering flags with auto(). Inserting a member between existing ones shifts the values after it, so a stored 8 changes meaning. Fix: assign explicit powers of two and append new members.
  • Overflow checks after the fact. In C the compiler may delete a check such as a + b < a. Fix: test b > 0 && a > INT_MAX - b before the addition.

Interview tips

Open by naming the type and its width and signedness, then the identity you rely on, such as two's complement negation or XOR self-cancellation.

Expect these follow-ups: what changes past 64 elements; what breaks for negative inputs and for n = 0; why the loop is O(set bits); what changes when an element appears three times; why the XOR swap fails when both operands alias.

30-second outline: Represent the set as a mask over N items. Each step isolates the lowest set bit with x & -x, processes it, and clears it with x &= x - 1, so cost follows the number of set bits, not the width. Submasks come from sub = (sub - 1) & m, which visits each subset once; summed over all masks that is 3^n. I would state the width, check the sign before shifting, and use a bitset only while the universe fits the word.

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.