Engineering platform~18 min2s · 256 MBtarget O(n + q) time, O(n) spaceprefix-sums · bit-manipulation
You work on a platform team that ships many deploys. Each deploy carries a mask of up to 29 feature flags. Every flag in the mask is toggled: an off flag turns on, and an on flag turns off.
An auditor asks: "If every flag started off and only the deploys from l to r were applied, how many flags would be on?" The history has up to 100,000 deploys and 100,000 questions.
Write flags_on_after(masks, ranges).
masks[i] is the mask of deploy i. Bit b of the mask is set when the deploy toggles flag b.[l, r] with 0 ≤ l ≤ r. Start with every flag off, and apply the deploys l to r, both included.Input: masks = [5, 3, 6, 1, 7], ranges = [[0, 2], [1, 3], [2, 2], [0, 4]]
Output: [0, 1, 2, 2]The masks in binary are 101, 011, 110, 001, 111. A flag that is toggled an even number of times is back off, so only flags toggled an odd number of times stay on. That is the xor of the masks.
| Deploys | Flags toggled an odd number of times (binary) | Flags on |
|---|---|---|
| 0 to 2 | 000 | 0 |
| 1 to 3 | 100 | 1 |
| 2 to 2 | 110 | 2 |
| 0 to 4 | 110 | 2 |
The answers are 0, 1, 2, 2.
Input: masks = [0, 0], ranges = [[0, 1]]
Output: [0]Deploys with an empty mask toggle nothing, so no flag is on.
Input: masks = [3, 3, 3], ranges = [[0, 1], [0, 2]]
Output: [0, 2]The mask 3 toggles two flags. After two deploys both are off again, and after three they are on.
1 ≤ len(masks) ≤ 100,0000 ≤ masks[i] ≤ 536,870,911, which is 29 flags1 ≤ len(ranges) ≤ 100,0000 ≤ l ≤ r < len(masks)Applying every deploy of a range for every question can read 100,000 masks per question, so up to 10 billion reads. That is too slow for a 2-second limit. Toggling twice cancels out, so the effect of a range is the effect of a prefix xored with the effect of an earlier prefix. Two reads per question are enough.