DSA · Pro · Pattern 6 of 9
Bit Manipulation
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
Bit manipulation treats an integer as a vector of independent bits. The core tools are x & (x - 1) to clear the lowest set bit, x & -x to isolate it, XOR to cancel equal values, and shifts to build masks. Many problems become simple once each bit position is analysed separately: count how many numbers have a bit set, or notice that an operation preserves those counts. Prefix XOR values and parity masks turn subarray conditions into hash-map lookups. Signals include XOR, AND or OR in the statement, values up to 2^30, a demand for constant extra space, or parity conditions over a small alphabet. Per-bit solutions usually run in O(n log C).
bool hasBit(long long x, int b) { return (x >> b) & 1; }
long long lowBit(long long x) { return x & -x; }
int popcount(unsigned x) { return __builtin_popcount(x); }
// How many numbers have each bit set; then reason bit by bit
array<int, 31> bitCounts(const vector<int>& a) {
array<int, 31> cnt{};
for (int x : a)
for (int b = 0; b < 31; b++)
if ((x >> b) & 1) cnt[b]++;
return cnt;
}
// Enumerate every non-empty submask s of mask:
// for (int s = mask; s > 0; s = (s - 1) & mask) { ... }