KatInterview

Calculate Rolling Means from a Data Stream

Stacks & QueuesAuto-graded · 25 test cases
EasyAuto-gradedStacks & Queuessliding-windowqueuedeque

Last 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 k items have been processed so far, return the mean of all items seen up to this point.
  • If k or more items have been processed, return the mean of the most recent k items.

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^9
  • k is an integer. If k <= 0, raise ValueError("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.