memoryBit Manipulation

Bit Manipulation: when to spot it, explain it, and practice it

Bit manipulation is most useful when the problem really lives at the level of binary state: toggles, subsets, parity, masks, or compact transitions. The trick is to know when bits simplify the model rather than make it look clever.

Pattern coverage

30+

Best first move

Choose whether bits represent membership, parity, or state flags.

Common failure point

Using bit tricks without a clean model behind them.

When this pattern should come to mind

The problem talks about subsets, masks, parity, or binary states explicitly.
A small n suggests subset enumeration over bitmasks.
XOR, AND, or bit counts can replace heavier data structures.

Checklist before you code

Choose whether bits represent membership, parity, or state flags.
Write one example mask by hand before coding.
Be careful with sign behavior and language-specific shifts.
Prefer simple bit operations over magic expressions you cannot explain.

The solving flow that works well in interviews

1

Define what each bit means.

2

Pick the one operation that naturally updates that meaning.

3

Use masks to compress repeated state if n is small enough.

4

Check one or two hand-worked examples.

5

Keep the final code explainable in plain language.

Common variants

Unique-number logic

Use XOR to cancel duplicates and isolate the answer.

Bitmask enumeration

Represent a subset or configuration as bits.

Bit DP / transitions

Use masks as DP states when the dimension is small.

Template preview

PythonPublic preview
x & (x - 1)        # clear lowest set bit
x & -x             # isolate lowest set bit
x | (1 << i)       # set bit i
x & ~(1 << i)      # clear bit i
x ^ (1 << i)       # toggle bit i
(x >> i) & 1       # read bit i

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Using bit tricks without a clean model behind them.

warning

Forgetting operator precedence in mixed expressions.

warning

Ignoring sign issues in languages with fixed-width integers.

warning

Overcomplicating a problem that would be simpler with arrays or sets.

Recommended practice path

1

Start with single number and counting bits.

2

Then solve sum without plus and subset enumeration.

3

Add simple bitmask DP after that.

4

Finish with harder compression problems only when the basics feel natural.

Bit Manipulation Pattern Guide | LeetCode Interview Prep - Interview AiBox