Practice problem · easy
A live video page shows how many viewers are watching. A counter reports the viewer count once a minute, and a chart beside it shows a moving average, so one small spike does not make the line jump.
For each report, the chart needs the average of the last k reports. Early in a show, fewer than k reports exist, so it uses all of them. A show can send up to 100,000 reports.
Write moving_averages(counts, k).
counts is a list of viewer counts, one for each minute, oldest first.k is how many of the latest reports to average.k reports, or of all reports so far when fewer than k exist. Round it down to a whole number.Input: counts = [10, 20, 30, 40], k = 2
Output: [10, 15, 25, 35]| Step | Report | Window (front to back) | Sum | Average |
|---|---|---|---|---|
| 1 | 10 |
10 |
10 | 10 |
| 2 | 20 |
10 20 |
30 | 15 |
| 3 | 30 |
20 30 (the 10 left) |
50 | 25 |
| 4 | 40 |
30 40 (the 20 left) |
70 | 35 |
The last report joins the window and the oldest one leaves, so the window slides one step at a time.
Input: counts = [7], k = 3
Output: [7]Only one report exists, so the average is that report.
Input: counts = [5, 6, 6, 5], k = 10
Output: [5, 5, 5, 5]Fewer than k reports exist at every step, so each average uses all of them: 5, then 11 / 2 rounded down, then 17 / 3, then 22 / 4.
1 ≤ length of counts ≤ 10^50 ≤ counts[i] ≤ 10^61 ≤ k ≤ 10^5A plan that adds up the last k reports again for every report costs about n times k steps. With n and k both near 10^5, that is 10^10, which is too slow.
So keep a running sum. When one report arrives and one leaves, the sum changes by two numbers, and no re-adding is needed.
moving_averages · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.