Music streaming app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceintervals · sorting
A live-streaming app logs each viewer's session: the minute they joined and the minute they left. A viewer who leaves at minute 5 is gone when minute 5 begins.
The producers want the peak audience, and also the first minute when it was reached, so that they can find that moment in the recording.
Write peak_viewers(joins, leaves).
i is watching during the minutes from joins[i] up to, but not including, leaves[i]. The sessions are not sorted.[peak, first], where first is the earliest minute at which that peak is reached.Input: joins = [0, 5, 3, 8, 6], leaves = [4, 9, 7, 12, 10]
Output: [3, 6]The trace sorts the joins and the leaves on their own. Joins: 0, 3, 5, 6, 8. Leaves: 4, 7, 9, 10, 12.
| Join minute | Leaves up to this minute | Joined so far | Gone | Audience | Peak so far |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 1 | 1 at 0 |
| 3 | 0 | 2 | 0 | 2 | 2 at 3 |
| 5 | 1 (the leave at 4) | 3 | 1 | 2 | 2 at 3 |
| 6 | 1 | 4 | 1 | 3 | 3 at 6 |
| 8 | 2 (the leaves at 4 and 7) | 5 | 2 | 3 | 3 at 6 |
The peak is 3 viewers, first reached at minute 6, so the output is [3, 6].
Input: joins = [2, 4], leaves = [4, 6]
Output: [1, 2]One viewer leaves at minute 4, and the other joins at minute 4. They never watch together.
Input: joins = [7, 7, 7], leaves = [8, 9, 10]
Output: [3, 7]All three viewers join at minute 7, so the audience is 3 at that minute.
1 ≤ joins.length ≤ 100,000 (sessions); leaves has the same length0 ≤ joins[i] < leaves[i] ≤ 1,000,000 (minutes of the event)Counting the viewers at every join minute costs n × n, about 10^10 steps. Sorting the joins and the leaves on their own costs n log n. Then one walk over the joins tells you how many have joined and how many have left at each minute.