Music streaming app~40 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-480heaps
A live video page reports its viewer count once a minute. A dashboard shows the median of the last k reports, so one short spike does not hide the usual audience. Each minute the window moves one step: the oldest report leaves and the new one joins.
A long event can send 100,000 reports, and k can be 50,000. Sorting every window again is too slow. A heap makes the median cheap to read, but it cannot take out a report from the middle.
Write window_medians(reports, k).
reports[i] is the viewer count reported in minute i.k reports in a row. There are len(reports) - k + 1 windows, from the first k reports to the last k.k is odd, it is the middle count. If k is even, it is the average of the two middle counts, rounded down to a whole number.Input: reports = [4, 9, 2, 7, 5, 1, 8, 6], k = 3
Output: [4, 7, 5, 5, 5, 6]Keep the lower half in a max-heap and the upper half in a min-heap. A report that leaves is not removed at once. It is counted as waiting, and it is popped when it reaches the top of a heap. The table shows each heap as it is stored, including waiting reports.
| Report in | Report out | Lower heap | Upper heap | Waiting to leave | Median |
|---|---|---|---|---|---|
| 4 | 4 | window not full | |||
| 9 | 4 | 9 | window not full | ||
| 2 | 2, 4 | 9 | 4 | ||
| 7 | 4 | 2, 7 | 9 | 7 | |
| 5 | 9 | 2, 5 | 7 | 5 | |
| 1 | 2 | 1, 2, 5 | 7 | 2 | 5 |
| 8 | 7 | 1, 2, 5 | 8 | 2 | 5 |
| 6 | 5 | 1, 6 | 8 | 6 |
In the last row, 5 leaves from the top of the lower heap. Then 2 reaches the top, and it is popped as well, because it was waiting.
Input: reports = [2000000000, 2000000000, 2000000000], k = 2
Output: [2000000000, 2000000000]Two counts add up to 4 × 10^9, which is larger than the largest int, 2,147,483,647. The median is still 2,000,000,000.
Input: reports = [1, 2, 3, 3], k = 2
Output: [1, 2, 3]The first two averages are 1.5 and 2.5, and rounded down they are 1 and 2.
1 ≤ length of reports ≤ 10^50 ≤ reports[i] ≤ 2 × 10^91 ≤ k ≤ length of reportsTwo counts can add up to 4 × 10^9, which does not fit in a 32-bit int (the largest is about 2.147 × 10^9). Java and C++ need 64-bit arithmetic for the sum of the two middle counts.
The length, 10^5, with a window that can be 50,000 long, rules out sorting every window. That costs about 4 × 10^10 steps. A sorted list that inserts and removes by position moves up to 5 × 10^9 values.