Moving Average of the Last N Order Values in a Live Feed
Last updated: November 29, 2026
Quick Overview
Orders arrive one at a time with a dollar value. Implement a class whose next(value) call returns the average of the most recent N values (or of all values if fewer than N have arrived) in O(1) time.
Amazon
November 29, 20260
0
0 solved
Orders arrive one at a time with a dollar value. Implement a class whose next(value) call returns the average of the most recent N values (or of all values if fewer than N have arrived) in O(1) time.
Retail dashboards show rolling order value to spot anomalies during events like Prime Day. The interviewer is checking that you maintain a running sum with a bounded queue rather than re-summing the window on every call.
What the Interviewer Expects
- Store the last N values in a deque or circular buffer
- Keep a running sum updated on insert and eviction
- Return sum divided by current window size
- O(1) time per call and O(N) space
- Mention floating point drift and integer cents
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you compute an exponentially weighted moving average instead, and what does it save?
- How would you support a time-based window (last 5 minutes) instead of a count?
- How would you keep many such averages, one per product, with bounded memory?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: window size N >= 1 at construction, then a sequence of next(value) calls. Output: after each call, the average over the latest min(N, count) values. Values can be large; use integer cents to ...
High-Level Design
Keep a deque of the window and an integer total. On next(v), append v and add it to total; if the deque now exceeds N, pop the oldest and subtract it. Return total / len(window). A fixed array...