Search~15 min2s · 256 MBtarget O(q) time, O(1) spacebit-manipulation
A search service keeps 30 feature flags in one number. Bit 0 is the first flag, and a bit is 1 when the flag is on.
The settings team applies a long list of group changes. Each change picks a stretch of flags, from flag low to flag high, and toggles every flag in it: on becomes off, and off becomes on. Your team lead asks: "What does the flag word look like after all the changes?"
Write final_flags(word, lows, highs).
word is the starting flag word.lows and highs describe the changes in order. Change i toggles every flag from lows[i] to highs[i], both included. It always holds that lows[i] ≤ highs[i].Input: word = 10, lows = [0, 1, 2], highs = [1, 3, 2]
Output: 3The word 10 is 1010 in binary. Each change builds a mask with ones on its flags, and the masks combine with XOR, because toggling a flag twice puts it back.
| Operation | Mask | Toggles so far |
|---|---|---|
| flags 0 to 1 | 0011 |
0011 |
| flags 1 to 3 | 1110 |
1101 |
| flags 2 to 2 | 0100 |
1001 |
The combined toggles are 1001, and 1010 XOR 1001 is 0011, which is 3.
Input: word = 5, lows = [0, 0], highs = [0, 0]
Output: 5Toggling flag 0 twice puts it back, so the word does not change.
Input: word = 0, lows = [0], highs = [29]
Output: 1073741823Toggling all 30 flags of an empty word turns on every flag: 2^30 − 1.
0 ≤ word < 2^301 ≤ len(lows) = len(highs) ≤ 800,0000 ≤ lows[i] ≤ highs[i] ≤ 29Toggling the flags of each change one by one costs up to 30 steps for each of 800,000 changes. Testing 64 positions each costs 51,200,000 steps. A mask with ones from low to high comes from two shifts and one subtraction, and XOR folds it in, so each change costs a few steps.