Leetcode #346: Moving Average from Data Stream
In this guide, we solve Leetcode #346 Moving Average from Data Stream in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement the MovingAverage class: MovingAverage(int size) Initializes the object with the size of the window size.
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Design, Queue, Array, Data Stream
Intuition
We need level-order exploration or shortest-step expansion, which maps directly to a queue.
BFS guarantees the first time you reach a node is the shortest in unweighted graphs.
Approach
Initialize the queue with starting nodes and expand outward layer by layer.
Track visited nodes to avoid cycles and redundant work.
Steps:
- Initialize a queue with start nodes.
- Pop, process, and enqueue neighbors.
- Track visited nodes.
Example
Input
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]
Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
Python Solution
class MovingAverage:
def __init__(self, size: int):
self.s = 0
self.data = [0] * size
self.cnt = 0
def next(self, val: int) -> float:
i = self.cnt % len(self.data)
self.s += val - self.data[i]
self.data[i] = val
self.cnt += 1
return self.s / min(self.cnt, len(self.data))
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
Complexity
The time complexity is , and the space complexity is , where is the integer given in the problem. The space complexity is , where is the integer given in the problem.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.