Ad platform~30 min2s · 256 MBtarget O(n) time, O(1) spacebit-manipulation
An ad server packs nine small counters of a campaign into one number. Each counter is a lane of 3 bits, so it counts from 0 to 7. Lane 0 is the lowest 3 bits, lane 1 the next 3, and so on.
When two servers merge their counts, each lane adds the two values, and a lane that would pass 7 stays at 7. Your team lead asks: "After merging every pair of words, what is the total of all the merged words?"
Write merged_total(a, b).
a and b are lists of the same length. Entry i of each is a packed word of nine lanes, each lane 3 bits.i, merge a[i] and b[i] lane by lane: the new lane is the sum of the two lanes, or 7 if the sum is above 7. A lane never carries into its neighbour.Input: a = [491], b = [84]
Output: 511The words are a = 491 and b = 84. The table shows the first three lanes. The other six lanes are 0 in both words.
| Lane | Lane in a |
Lane in b |
Sum | Merged (capped at 7) |
|---|---|---|---|---|
| 0 | 3 | 4 | 7 | 7 |
| 1 | 5 | 2 | 7 | 7 |
| 2 | 7 | 1 | 8 | 7 |
The merged lanes are 7, 7 and 7, so the merged word is 511. A plain addition a + b would carry out of lane 2 into lane 3.
Input: a = [0], b = [0]
Output: 0Two empty words merge into an empty word.
Input: a = [7], b = [7]
Output: 7The lanes 7 and 7 add to 14, which is capped at 7. The word 7 only has lane 0 set, so the result is 7.
1 ≤ len(a) = len(b) ≤ 500,0000 ≤ a[i], b[i] < 2^27Adding the lanes with a full adder costs 3 bit steps for each of 9 lanes. That is 13,500,000 steps in all for 500,000 pairs. A few masks and bit operations add all nine lanes at once, in about 12 operations for each pair.