Compute moving average over last N stream
AtlassianMachine Learning Engineer · OnsiteLast updated
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)?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.