Chat app~20 min2s · 256 MBtarget O(n + day_length) time, O(day_length) spacesliding-window-variable
A chat app sends a daily digest to its users, and it wants to send it when the chat is quiet. The app logs the second of the day at which each message event happened.
A period counts as quiet when it has at most k events. The team wants the longest run of consecutive seconds that is quiet, so the digest has the most room.
Write longest_quiet_period(events, day_length, k).
day_length seconds, numbered 0 to day_length - 1. Each value of events is the second of one event, in any order. Several events can share a second, and each counts.k events in total.k is large enough, that is the whole day.Input: events = [1, 2, 2, 6, 7, 10], day_length = 12, k = 1
Output: 4The trace slides a window over the seconds, and keeps at most 1 event inside.
| Second | Events in it | Window | Events in window | Longest so far |
|---|---|---|---|---|
| 0 | 0 | 0 to 0 | 0 | 1 |
| 1 | 1 | 0 to 1 | 1 | 2 |
| 2 | 2 | 3 to 2 | 0 | 2 |
| 3 | 0 | 3 to 3 | 0 | 2 |
| 4 | 0 | 3 to 4 | 0 | 2 |
| 5 | 0 | 3 to 5 | 0 | 3 |
| 6 | 1 | 3 to 6 | 1 | 4 |
| 7 | 1 | 7 to 7 | 1 | 4 |
| 8 | 0 | 7 to 8 | 1 | 4 |
| 9 | 0 | 7 to 9 | 1 | 4 |
| 10 | 1 | 8 to 10 | 1 | 4 |
| 11 | 0 | 8 to 11 | 1 | 4 |
The window from second 3 to second 6 holds one event, the one at second 6. No window with at most 1 event is longer, so the answer is 4.
Input: events = [0, 5, 5], day_length = 10, k = 0
Output: 4With k = 0, no event may be inside. The longest gap is seconds 6 to 9, which has 4 seconds.
Input: events = [3, 3, 3], day_length = 6, k = 3
Output: 6Three events are allowed, and there are exactly three events. The whole day of 6 seconds is quiet.
1 ≤ events.length ≤ 100,0000 ≤ events[i] < day_length1 ≤ day_length ≤ 86,400 (seconds in a day)0 ≤ k ≤ 100,000Checking every pair of start and end seconds, and counting the events inside, costs about day_length² / 2 pairs, about 3.7 × 10^9 for a whole day. Counts are never negative, so a window can grow on the right and shrink on the left. Each second then enters and leaves once: about 2 × 86,400 steps.