Social feed~35 min2s · 256 MBtarget O(n) time, O(n + filter_bits / 32) spacebit-manipulation · hashing
A feed shows how many different people read each post. Storing every reader id of a post that millions of people open costs too much memory, so the team tests a smaller design.
It keeps a block of filter_bits bits, all 0 at first. Each reader id points to three bit positions. If all three bits are already 1, the filter says "seen before". Otherwise it counts a new reader and sets the three bits to 1.
Two different readers can point to the same bits, so the filter sometimes says "seen before" for a reader it has not met. You report how large that error is.
Write count_with_filter(readers, filter_bits).
readers[i] is the id of the i-th reader to open the post. The same id can appear many times.r points to these three positions, each from 0 to filter_bits − 1:
r mod filter_bits(r × 31 + 7) mod filter_bits(r × 131 + 13) mod filter_bits[0, 0].Input: readers = [25, 24, 66, 25, 61, 81, 79], filter_bits = 16
Output: [5, 1]The trace shows the three positions of each reader and whether all three bits were already 1.
| Reader | Positions | All three bits already 1? | Counted so far |
|---|---|---|---|
| 25 | 9, 14, 8 | no, set them | 1 |
| 24 | 8, 15, 5 | no, set them | 2 |
| 66 | 2, 5, 3 | no, set them | 3 |
| 25 | 9, 14, 8 | yes, seen before | 3 |
| 61 | 13, 10, 4 | no, set them | 4 |
| 81 | 1, 6, 0 | no, set them | 5 |
| 79 | 15, 8, 10 | yes, by mistake | 5 |
Reader 79 has never opened the post.
Its bit 15 was set by reader 24, its bit 8 by readers 25 and 24, and its bit 10 by reader 61. The ids are 25, 24, 66, 61, 81 and 79, so there are 6 different readers. The filter counted 5 of them, so it missed 1. The output is [5, 1].
Input: readers = [7, 7, 7], filter_bits = 32
Output: [1, 0]The first visit sets the bits 7, 0 and 2. The next two visits find all three bits set. One different reader, counted once.
Input: readers = [1, 6], filter_bits = 16
Output: [2, 0]Reader 1 sets bits 1, 6 and 0. Reader 6 points to bits 6, 1 and 15. Two of them are already 1, but bit 15 is not, so reader 6 is counted as new.
0 ≤ readers.length ≤ 100,000 (visits to one post)0 ≤ readers[i] ≤ 1,000,000,0008 ≤ filter_bits ≤ 1,000,000Keeping the set bits and the readers in plain lists and searching them for every visit costs about n × n / 2 steps. For 100,000 visits that is about 5 × 10^9, far over the budget of about 10^8 a second. Testing and setting a bit costs one step, so the pass costs about n steps.