Bit manipulation and modular arithmetic
CS · Chapter 711 min readAsked at Hudson River Trading, Jump, Tower, Optiver
Assumes Core techniques: binary search on the answer, two pointers, sliding windows.
After this lesson you should be able to
- Use the standard bit tricks and say what each does.
- Apply XOR properties to find a missing or unpaired element.
- Compute a large power modulo efficiently.
Bit manipulation turns up in two places: as a puzzle in interviews, and as a genuine optimisation on a latency-sensitive path where a branch or a division is too expensive. Both reward knowing a short list of identities cold.
| Expression | Does | Note |
|---|---|---|
| Clears the lowest set bit | Loop on it to count set bits | |
| Isolates the lowest set bit | The basis of the Fenwick tree | |
| Tests for a power of two | Careful with zero | |
| Differs where they differ | Self-inverse: | |
| , | Multiply or divide by | Beware sign on right shift |
| Sets bit | And clears it |
Why XOR solves the pairing puzzles. XOR has three properties that together do all the work: it is its own inverse, it is commutative and associative, and zero is the identity. So XOR-ing a whole collection cancels everything that appears an even number of times, whatever the order, and leaves whatever appeared an odd number of times. "Find the element that appears once among pairs" and "find the missing number from 1 to " are the same problem, both solved in one pass with constant memory — and no sorting, hashing or extra space.
Example 7.2
An array holds every number from to except one. Find the missing one in time and space, two ways.
Show the worked solutionHide the worked solution
Worked solution
- Formula
- Substitute
- Solve
- Answer
Sanity check. The XOR version is preferable in production because the sum can overflow for large while the XOR cannot. That is exactly the kind of detail a low-latency interviewer is looking for.
Proposition 7.3
Modular arithmetic
Addition and multiplication commute with taking a remainder, so you can reduce at every step and never overflow. Division does not: dividing modulo means multiplying by a modular inverse, which exists only when the divisor and are coprime.
Holds when
- , and likewise for products.
- Fermat: when is prime, .
- Negative remainders differ by language — C and Python disagree, and it is a real source of bugs.
The rest of this lesson is in Premium
You have read the opening. 12 more sections follow, including 4 worked examples and 3 quick checks.
Nothing is charged for 7 days, and you can cancel before then. Or read Complexity: reading it off, and deriving it in full, free.