Ad platform~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-190bit-manipulation
An ad server runs each campaign on a weekly schedule of width time slots. A schedule is stored as a mask: bit 0 is the first slot, and a bit is 1 when the campaign runs in that slot.
A schedule is symmetric when it reads the same from the first slot to the last as from the last slot to the first. Your team lead asks: "How many campaigns have a symmetric schedule?"
Write count_symmetric_schedules(masks, width).
masks is the list of schedule masks, one for each campaign. Each mask uses only its lowest width bits.width bits, so bit i moves to bit width - 1 - i. Slots with no bit set still count, so leading zeros matter.Input: masks = [129, 176, 24, 65], width = 8
Output: 2Write each mask with 8 bits, reverse the 8 digits, and compare. The masks 129 and 24 are symmetric.
| Mask | 8 bits | Mirror image | Symmetric? |
|---|---|---|---|
| 129 | 10000001 | 10000001 | yes |
| 176 | 10110000 | 00001101 | no |
| 24 | 00011000 | 00011000 | yes |
| 65 | 01000001 | 10000010 | no |
Input: masks = [0], width = 1
Output: 1With one slot, the mask 0 is its own mirror image.
Input: masks = [1, 2, 3], width = 2
Output: 1With 2 slots, only 11 reads the same both ways: 01 mirrors to 10, and 10 to 01.
1 ≤ len(masks) ≤ 700,0001 ≤ width ≤ 290 ≤ masks[i] < 2^widthMoving the bits of every mask one at a time costs one step for each position, which is 44,800,000 steps for 700,000 masks when 64 positions are tested. A table of the mirror images of all 256 byte values mirrors a 32-bit word with 4 look-ups, so the whole list costs about 2,800,000 look-ups.