You are processing a stream of numeric events (e.g., user activity counts). You are given a fixed window size X.
Part 1: Moving average over last X values
Design a data structure / function that supports:
where avg is the average of the most recent X values seen so far (or fewer than X if fewer values have arrived).
Part 2 (follow-up): Weighted moving average
Modify the approach to compute a weighted moving average over the most recent X values where more recent values have higher weight.
For example, for the last k <= X values (oldest to newest):
-
weights could be
1, 2, ..., k
-
weighted average =
∑i=1ki∑i=1ki⋅vi
Constraint
Do this without storing all previous data points (i.e., memory should not grow with the total stream length).