Music streaming app~15 min2s · 256 MBtarget O(n) time, O(1) spacesliding-window-fixed
A music streaming app draws a smoothed chart of plays. For each minute it stores the number of play starts. The chart shows, for every stretch of k minutes in a row, the total plays in that stretch.
An earlier version of the chart code had an off-by-one error: its last point was missing, and some points were wrong. You write the version that gets every window right, and you check it by tracing a small example by hand.
Write window_totals(counts, k).
counts[i] is the number of play starts in minute i.k minutes in a row: minutes s to s + k - 1, for each start s from 0 up to counts.length - k.s.k is larger than counts.length, there is no window: return an empty list.Input: counts = [5, 1, 4, 2, 6, 3, 2], k = 3
Output: [10, 7, 12, 11, 11]There are 7 minutes, so there are 7 - 3 + 1 = 5 windows.
| Window start s | Minutes | Total |
|---|---|---|
| 0 | 0 to 2 | 5 + 1 + 4 = 10 |
| 1 | 1 to 3 | 1 + 4 + 2 = 7 |
| 2 | 2 to 4 | 4 + 2 + 6 = 12 |
| 3 | 3 to 5 | 2 + 6 + 3 = 11 |
| 4 | 4 to 6 | 6 + 3 + 2 = 11 |
Input: counts = [9, 9], k = 2
Output: [18]One window covers both minutes.
Input: counts = [3, 9], k = 4
Output: []The window is longer than the data, so there is no window.
1 ≤ counts.length ≤ 100,000 (minutes of data)0 ≤ counts[i] ≤ 1,000,000 (play starts in one minute)1 ≤ k ≤ 100,000 (minutes in a window)Adding the k minutes of every window costs up to n × k steps: 100,000 × 50,000 is 5 × 10^9 at its worst. That is too slow. Reuse the previous window: one value leaves and one joins. A window total can reach 10^11, so it needs a 64-bit integer.