Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spacewindow-counts · hashing
You work on a chat app. A busy group chat shows a small badge: how many different people wrote in the last few seconds. The badge must be updated after every message.
Messages arrive in time order, and several can share one second. A message counts in the badge for span seconds, including the second in which it was sent. Your team lead asks: "What does the badge show after each message?"
Write distinct_in_last(times, senders, span).
times[i] is the second in which message i was sent. The times are in non-decreasing order.senders[i] is the id of the person who sent message i.i, the badge counts the messages j ≤ i with times[j] > times[i] - span. That is the last span seconds, including second times[i].Input: times = [1, 2, 2, 4, 6, 7, 7], senders = [5, 3, 5, 5, 3, 9, 5], span = 3
Output: [1, 2, 2, 2, 2, 2, 3]| Message | Second | Sender | Messages counted (their senders) | Different senders |
|---|---|---|---|---|
| 0 | 1 | 5 | 0 (5) | 1 |
| 1 | 2 | 3 | 0, 1 (5, 3) | 2 |
| 2 | 2 | 5 | 0, 1, 2 (5, 3, 5) | 2 |
| 3 | 4 | 5 | 1, 2, 3 (3, 5, 5) | 2 |
| 4 | 6 | 3 | 3, 4 (5, 3) | 2 |
| 5 | 7 | 9 | 4, 5 (3, 9) | 2 |
| 6 | 7 | 5 | 4, 5, 6 (3, 9, 5) | 3 |
At second 4, the badge counts the seconds 2, 3 and 4, so message 0 (second 1) has left.
Input: times = [10], senders = [8], span = 5
Output: [1]Input: times = [3, 3, 3], senders = [1, 1, 2], span = 1
Output: [1, 1, 2]With span = 1 the badge counts only the current second, and messages of the same second are all in.
1 ≤ times.length = senders.length ≤ 200,000 (messages)0 ≤ times[i] ≤ 1,000,000,000, in non-decreasing order1 ≤ senders[i] ≤ 1,000,000,0001 ≤ span ≤ 1,000,000,000If all messages fall in one window, then after each message you would look back through all earlier messages. That is about 20,000,000,000 steps in all.
Each message enters the window once and leaves it once. With a count for each sender, 200,000 messages cost about 400,000 window updates.