Pattern

Bit manipulation

Replace a per-element or per-digit loop with operations that act on every bit of a machine word at once.

What it is

Bit manipulation problems ask you to compute something about the binary representation of an integer, or to use bitwise operators (&, |, ^, shifts) to simulate arithmetic or cancel out values, in place of an operator or loop you'd normally reach for. The technique rests on a handful of reusable identities — XOR cancels equal values and is its own inverse, n & (n - 1) clears the lowest set bit, subtracting one flips a specific run of bits — each of which turns an operation that looks like it needs a full scan into a constant number of word-level operations. The hard part is rarely the operator itself; it's recognizing which identity matches the structure of the problem, and handling the fact that most languages (Python especially) don't naturally bound integers to a fixed width the way real hardware does.

When it applies

Tells in the problem

The classic mistake

The recurring bug is writing bit-manipulation code as if the language enforces a fixed word width when it doesn't — in Python, a loop that shifts a value right until it becomes zero never terminates on a value that's meant to represent a negative number in two's complement, because Python integers have no top bit to run out of. The fix is to explicitly mask every intermediate value to the stated width (& 0xFFFFFFFF) and reinterpret the final pattern as signed only at the end, rather than assuming the arithmetic "just works" the way it would in C or Java. A second common mistake is reaching for a bit trick that only works for the case shown in the prompt — treating a "cancel in pairs" XOR solution as if it generalizes to "cancel in triples" without changing the accumulator, when the triples case actually needs a per-bit count mod 3, not XOR at all.

Questions to start with

All 5 bit manipulation questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.