Calculate Rolling Means from a Data Stream
Stacks & QueuesAuto-graded · 25 test casesLast updated
Evaluate tracking a sliding window over incoming numbers to incrementally update and output moving averages.
Given a fixed capacity parameter k and a sequence of incoming numbers a, calculate the floating-point average of the numbers within a sliding window of maximum size k after each value is processed.
Specifically, as each element from a arrives:
- If fewer than
kitems have been processed so far, return the mean of all items seen up to this point. - If
kor more items have been processed, return the mean of the most recentkitems.
If k <= 0, raise a ValueError.
Return a list of floats representing the window mean computed after each step.
Constraints
1 <= len(a) <= 10^5-10^9 <= a[i] <= 10^9kis an integer. Ifk <= 0, raiseValueError("k must be positive").
Examples
Example 1
Input: moving_average(3, [1, 2, 3, 4, 5])
Output: [1, 1.5, 2, 3, 4]
Example 2
Input: moving_average(2, [10, 20, 30, 40])
Output: [10, 15, 25, 35]
Example 3
Input: moving_average(4, [5, -1, 7])
Output: [5, 2, 3.6666666666666665]
Hints
Hint 1
Instead of re-summing all elements in the window at every step, keep a running total.
Hint 2
Use a doubly linked queue (or fixed-size ring buffer) to maintain the window elements so that inserting new items and removing evicted ones takes O(1) time.
Hint 3
When the window size exceeds k, drop the oldest element and subtract its value from the running total.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To compute moving averages efficiently across a data stream without repeatedly summing elements from scratch:
- Maintain a double-ended queue (
deque) to track the values currently inside the active window. - Maintain a variable
running_sumrepresenting the exact sum of all elements in the currentdeque. - For each incoming element
valin arraya:- Append
valto the queue and addvaltorunning_sum. - If the size of the queue exceeds
k, pop the front element from the queue and subtract its value fromrunning_sum. - Compute the floating-point average by dividing
running_sumby the current size of the queue (len(window)), and append it to the result list.
- Append
Using a deque allows both appends at the back and evictions from the front in $O(1)$ time, maintaining optimal computational performance throughout the sequence.
Complexity
- Time Complexity: $O(N)$ where $N$ is the length of array
a. Each element is added to and removed from the queue at most once, requiring $O(1)$ amortized work per step. - Space Complexity: $O(k)$ auxiliary space for storing up to $k$ elements in the active window (excluding the $O(N)$ space required for the output list).
from collections import deque
from typing import List
def moving_average(k: int, a: List[int]) -> List[float]:
if k <= 0:
raise ValueError("k must be positive")
window = deque()
running_sum = 0
averages = []
for val in a:
window.append(val)
running_sum += val
if len(window) > k:
running_sum -= window.popleft()
averages.append(running_sum / len(window))
return averages