Payments app~15 min2s · 256 MBtarget O(n + shards) time, O(n + shards) spacehashing
A payments app spreads its payment records over a number of database shards. A payment goes to the shard numbered id mod shards, which is the remainder when its id is divided by the shard count.
Clients retry failed requests, so one payment id can arrive several times, and the payment must count only once. Operations wants to know which shard holds the most distinct payments.
Write busiest_shard(ids, shards).
ids[i] is the payment id of the i-th request. Ids repeat when a client retries.shards is the number of shards, numbered 0 to shards - 1.x lives in shard x % shards. Count each distinct id once.Input: ids = [14, 9, 14, 21, 6, 9, 30], shards = 5
Output: 1Shard numbers are id % 5. The trace keeps a set of ids already counted.
| i | id | Seen before | Shard | counts after |
|---|---|---|---|---|
| 0 | 14 | no | 4 | 0, 0, 0, 0, 1 |
| 1 | 9 | no | 4 | 0, 0, 0, 0, 2 |
| 2 | 14 | yes: a retry | 0, 0, 0, 0, 2 | |
| 3 | 21 | no | 1 | 0, 1, 0, 0, 2 |
| 4 | 6 | no | 1 | 0, 2, 0, 0, 2 |
| 5 | 9 | yes: a retry | 0, 2, 0, 0, 2 | |
| 6 | 30 | no | 0 | 1, 2, 0, 0, 2 |
Shards 1 and 4 both hold two distinct payments. The smaller number, 1, is the answer.
Input: ids = [5, 10, 15], shards = 5
Output: 0All three ids are multiples of 5, so all of them go to shard 0.
Input: ids = [7], shards = 1
Output: 0One shard holds everything, and its number is 0.
1 ≤ ids.length ≤ 100,000 (requests in one batch)0 ≤ ids[i] ≤ 10^9 (payment ids)1 ≤ shards ≤ 100,000Checking each id against all the ids before it costs about n × n / 2 comparisons. At n = 100,000 that is about 5 × 10^9: far over the budget of about 10^8 simple operations a second. A hash set answers "seen before?" in one step on average, so the pass makes about n steps.
Read the values too. An id is at most 10^9, which fits in a 32-bit int, and id % shards needs no wider type.