Bit Manipulation: Bitwise identities and fixed-width integers
Goal: Learn the pattern first, then apply it to the 7 roadmap problems in this chapter.
When this pattern appears
The task involves parity, counts, missing values, or arithmetic on bit representations.
The reusable idea
Write the operation in binary and use cancellation, masks, shifts, or carry identities.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
Which bit identity eliminates state or combines matching values?
Common failure modes
Signed versus unsigned behavior, bit width, operator precedence, and negative values.
Chapter problems from the workbook
- #144 · Single Number — Day 86, Easy. Open problem ↗
- #145 · Number of 1 Bits — Day 86, Easy. Open problem ↗
- #146 · Counting Bits — Day 87, Easy. Open problem ↗
- #147 · Reverse Bits — Day 87, Easy. Open problem ↗
- #148 · Missing Number — Day 88, Easy. Open problem ↗
- #149 · Sum of Two Integers — Day 88, Medium. Open problem ↗
- #150 · Reverse Integer — Day 89, Medium. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.