The Moving Average from Data Stream problem asks you to design a class that computes the moving average of the last k elements of a data stream. Each time a new number arrives, add it to the window and remove the oldest if the window exceeds size k. Return the current average. This Moving Average from Data Stream coding problem tests circular buffer or queue design.
Nuro, Tesla, Citadel, Microsoft, Meta, Amazon, LinkedIn, Google, and Bloomberg ask this because moving averages are fundamental to real-time data processing, stock market analytics, and signal smoothing. The data stream, array, design, and queue interview pattern is the core, and the problem tests whether candidates can implement a sliding window cleanly with O(1) per-operation complexity.
Circular queue (deque or fixed array). Maintain a queue of the last k elements and a running sum. For each new value: add it to the sum and queue. If queue size > k, remove the oldest element from the front and subtract it from the sum. Return sum / min(count, k).
k = 3. Stream: [1, 10, 3, 5].
Moving average is the canonical sliding window with running sum design problem. The key insight: maintain a running sum and update it incrementally (add new, subtract old) instead of recomputing from the window each time. Use collections.deque for O(1) append and popleft operations. This incremental update pattern applies to any "window aggregate" — running sum, running max (harder), running count. Practice all three for a complete sliding window skillset.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Recent Calls | Easy | Solve | |
| Design Front Middle Back Queue | Medium | Solve | |
| Design Hit Counter | Medium | Solve | |
| First Unique Number | Medium | Solve | |
| Design an Ordered Stream | Easy | Solve |