Chat app~10 min2s · 256 MBtarget O(n) time, O(n) spacehashing
A chat app splits its message ids over shards. A shard hands out only the ids step, 2 x step, 3 x step and so on, always the smallest one that is still free. Over time, a record of issued ids has collected on disk. It can hold ids in any order, repeated ids, and ids from other shards.
Your team lead asks: what is the next id this shard should hand out?
Write first_free_id(issued, step).
issued is the record of ids, in any order. An id can appear more than once, and it need not be a multiple of step.step: step, 2 x step, 3 x step, and so on.step that does not appear in issued.Input: issued = [12, 3, 6, 5, 9, 3, 18], step = 3
Output: 15Try the multiples of 3 in order, and look each one up in the record.
| Multiple of 3 | In the record? |
|---|---|
| 3 | yes |
| 6 | yes |
| 9 | yes |
| 12 | yes |
| 15 | no |
The next free id is 15. The id 18 is issued, but it comes after the first gap, and 5 is not a multiple of 3.
Input: issued = [2, 4], step = 5
Output: 5None of the shard's ids is issued, so the first one, 5, is free.
Input: issued = [10, 5, 15, 20, 5], step = 5
Output: 25The ids 5, 10, 15 and 20 are all issued, and 5 appears twice. The next one is 25.
1 ≤ length of issued ≤ 10^51 ≤ issued[i] ≤ 10^91 ≤ step ≤ 1000Looking up each multiple by scanning the whole record costs up to 10^5 steps per lookup. With up to 10^5 multiples that is about 10^10 steps, too slow for a 2 second limit.
The record has at most n ids, so at most n multiples can be taken, and the answer is at most (n + 1) x step. That is at most about 10^8, which a 32-bit integer holds. A set answers each lookup in about one step.