Moving Average from Data Stream — LeetCode 346 Python Solution

EasyLeetCode PremiumDesignQueueArrayData Stream
Problem
#346
Pattern
Stack
Reading time
3 min

The problem

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.

Example

Input
["MovingAverage", "next", "next", "next", "next"]
Output
[null, 1.0, 5.5, 4.66667, 6.0]
Explanation
MovingAverage movingAverage = new MovingAverage(3);

Python solution

Python
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

MeasureComplexity
TimeO(1)
SpaceO(n), where n is the integer \textit{size} given in the problem auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 346. Moving Average from Data Stream is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 346. Moving Average from Data Stream?
LeetCode 346. Moving Average from Data Stream is rated Easy on LeetCode.
What is the time complexity of LeetCode 346. Moving Average from Data Stream?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 346. Moving Average from Data Stream?
The Python solution on this page uses O(n), where n is the integer \textit{size} given in the problem auxiliary space.
What topics does LeetCode 346. Moving Average from Data Stream cover?
LeetCode 346. Moving Average from Data Stream is tagged Design, Queue, Array and Data Stream on LeetCode.
Is LeetCode 346. Moving Average from Data Stream a premium problem?
Yes. LeetCode 346. Moving Average from Data Stream is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview