Coding questions · Atlassian
Compute moving average over last N stream
This question evaluates understanding of streaming algorithms and sliding-window aggregation within the Coding & Algorithms domain, focusing on incremental computation, state management, and numerical stability when computing moving averages.
You are given an integer N and an unbounded stream of integers arriving one by one. After each new integer arrives, output the average of the last N integers seen so far.
Requirements:
- If fewer than N integers have arrived, average over all integers seen so far.
- The solution should support efficient updates per element.
Follow-up:
- How would you modify the design if more recent numbers should have higher weight (e.g., exponentially decaying weights or a custom weight vector over the last N items)?
Moving Average over Last N Stream Values
Examples
Example 1
Input: (3, [1, 10, 3, 5])
Output: [1.0, 5.5, 4.666667, 6.0]
Explanation: Window grows then slides.
Example 2
Input: (1, [4, 5])
Output: [4.0, 5.0]
Explanation: Only latest value.