Chat app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-846greedy · sorting
You work on the sync service of a chat app. After a reconnect, a device sends the sequence numbers of the messages it has received, in any order, and some numbers appear twice.
The server stores them in batches. Each batch holds exactly group_size consecutive sequence numbers, such as 4, 5 and 6. Your team lead asks: "Can every number go into exactly one batch?"
Write groups_possible(sequence_numbers, group_size).
sequence_numbers can be in any order and can repeat values.group_size numbers that follow each other, such as x, x + 1, ..., x + group_size - 1.true when the whole list can be split into such batches, and false otherwise.Input: sequence_numbers = [12, 11, 13, 12, 14, 13], group_size = 3
Output: trueCount each value: 11 once, 12 twice, 13 twice, 14 once. Go through the values from the smallest. The smallest value that is left must start a batch.
| Smallest left | Batches started | Numbers used | Counts left (11, 12, 13, 14) |
|---|---|---|---|
| 11 | 1 | 11, 12, 13 | 0, 1, 1, 1 |
| 12 | 1 | 12, 13, 14 | 0, 0, 0, 0 |
Every number is used, so the answer is true.
Input: sequence_numbers = [1, 2, 3, 3, 4, 6], group_size = 3
Output: falseThe batch from 1 uses 1, 2 and 3. The smallest number left is 3, and its batch needs 4 and 5. There is no 5, so the answer is false.
Input: sequence_numbers = [7, 7, 7], group_size = 1
Output: trueA batch of 1 is a single number, so every list works.
1 ≤ len(sequence_numbers) ≤ 100,0000 ≤ sequence_numbers[i] ≤ 1,000,000,0001 ≤ group_size ≤ 100,000There can be 100,000 numbers. Trying every way to choose the numbers of each batch grows faster than any power of n. A sort costs about 1.7 million steps, and building and using the counts costs about 100,000 more steps. That fits easily.