Searching and lookup · Intermediate
Bit tricks and arithmetic invariants
Use algebra instead of storage: XOR cancels pairs, sums reveal a missing value, masks test bits, and Euclid shrinks a gcd in logarithmic steps.
On this page
The idea
Some lookups can be replaced by an identity. x XOR x = 0 and x XOR 0 = x, so XOR-ing a list where every value appears twice except one leaves that one. The sum 0 + 1 + … + n is n(n + 1)/2, so subtracting the actual sum from it reveals a single missing number. Neither needs a hash set.
Masks treat an integer as a small set of bits: x & (x − 1) clears the lowest set bit, x & −x isolates it, and 1 << i selects bit i. Euclid's gcd(a, b) = gcd(b, a mod b) at least halves the larger argument every two steps.
How to recognise it
- "Every element appears twice except one", "one number is missing from 0..n".
- Constraints demand O(1) extra space where a hash set would be the obvious answer.
- Counting bits, powers of two, subsets of a small set (n ≤ 20) encoded as masks.
- Divisibility, tiling, ratios: anything about common divisors.
When not to use it
- The identity relies on a property the input does not guarantee (exactly one missing value, exactly pairs): a hash set is safer.
- Readability matters more than the constant factor and memory is not tight.
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# The unpaired value
acc = 0
for x in a: acc ^= x
return acc
# Count set bits (Kernighan)
count = 0
while x != 0:
x &= x - 1 # clears the lowest set bit
count += 1
# Greatest common divisor
while b != 0: a, b = b, a % b
return a- Mind signed shifts and fixed widths: >> on negative numbers differs across languages; Java has >>> for unsigned shift.
- Sum formulas can overflow; XOR-based variants of "missing number" cannot.
Complexity
Time O(n) scans; O(set bits) popcount; O(log min(a, b)) gcd, extra space O(1). Each identity replaces a set or map with a single accumulator.
Worked examples
Unpaired value in [4, 1, 2, 1, 2]
4 ^ 1 = 5, ^ 2 = 7, ^ 1 = 6, ^ 2 = 4. The pairs cancel regardless of order, leaving 4.
Pitfalls
- Operator precedence: in C-family languages `x & 1 == 0` parses as `x & (1 == 0)`.
- Overflow when summing large ranges in 32-bit integers.
- Assuming >> is a logical shift for negative values.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemThe sock without a pair· beginner · O(n)
- ProblemThe one ticket that never came back· beginner · O(n)
- ProblemCount the 1 bits· beginner · O(number of 1 bits) ≤ O(width)
- ProblemThe largest tile that fits both walls· beginner · O(log min(a, b)) iterations
- ProblemThe one value not in a triple· advanced · O(n)
- ProblemSet bits for every number up to n· beginner · O(n)
Learn the foundations
Lessons
- ModuleM33 Bit Manipulation· intermediate
- ModuleM34 Math· intermediate
Related patterns
- PatternHashing for constant-time lookup· O(n) expected
- PatternOne pass with a running state· O(n)
References
dsa.pattern.bit-and-math-invariants · version 1