03
Range bitwise properties (Bit Manipulation Sub-pattern)
A bitwise operation over a range or a group of numbers, answered without touching every number again.
Signals in the problem statement
- ›
"XOR of arr[l..r]" for many queries
- ›
"bitwise AND of all numbers in [left, right]"
- ›
"largest group whose AND / OR is …"
What makes it different
XOR over ranges → prefix XOR (cancels like subtraction). AND over a range of consecutive numbers → the common prefix of the two ends, everything below it becomes 0. Group AND > 0 → some single bit is shared by the whole group; count per bit.
Questions
ordered from “learn the idea” to “recognise it without help”- 1XOR Queries of a SubarrayWalkthroughMediumBasic Anchor·LeetCode #1310
- 2Bitwise AND of Numbers RangeWalkthroughMediumBasic Reinforcement·LeetCode #201
- 3Largest Combination With Bitwise AND Greater Than ZeroWalkthroughMediumSlight Variation·LeetCode #2275
Template
range-bits-template.cpp
// XOR of a[l..r] in O(1) after O(N) setup: the shared prefix cancels.
struct PrefixXor {
vector<int> p; // p[i] = a[0] ^ ... ^ a[i-1], p[0] = 0
PrefixXor(const vector<int>& a) : p(a.size() + 1, 0) {
for (size_t i = 0; i < a.size(); i++) p[i + 1] = p[i] ^ a[i];
}
int query(int l, int r) const { return p[r + 1] ^ p[l]; }
};
// AND of every number in [left, right] = their common binary prefix.
// Each lower bit is 0 somewhere in the range, so it becomes 0.
int rangeAnd(int left, int right) {
int shift = 0;
while (left != right) { left >>= 1; right >>= 1; shift++; }
return left << shift;
}
// Largest group with AND > 0: the group must share one bit, so count per bit.
int largestSharingABit(const vector<int>& a) {
int best = 0;
for (int b = 0; b < 31; b++) {
int cnt = 0;
for (int v : a) cnt += (v >> b) & 1;
best = max(best, cnt);
}
return best;
}Remember this · Bit Manipulation
Trigger
"Every element appears twice except…", power of two, counting set bits, subsets as bitmasks, O(1) space tricks.
Think
What happens to this problem if I look at each bit separately?
Key question
Which bit operation (XOR, AND, OR, shift) cancels or isolates what I need?