LeetCode 346: Moving Average from Data Stream

link

We keep track of the window sum. If window has too many numbers we pop the oldest, updating sum.

OperationTimeSpace
__init__\mathcal{O}(1)\mathcal{O}(1)
next\mathcal{O}(1)\mathcal{O}(1)
class MovingAverage:

    def __init__(self, size: int):
        self.window = deque()
        self.size = size
        self.sum = 0

    def next(self, val: int) -> float:
        self.window.append(val)
        self.sum += val
        if len(self.window) > self.size:
            popped = self.window.popleft()
            self.sum -= popped
        
        return self.sum / len(self.window)


# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)

Leave a comment