Tags: "leetcode", "ood", "deque", "sliding-window", access_time 1-min read

Edit this post on Github

Moving Average From Data Stream

Created: March 21, 2020 by [lek-tin]

Last updated: March 21, 2020

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Example

MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

Solution

from collections import deque

class MovingAverage:

    def __init__(self, size: int):
        """
        Initialize your data structure here.
        """
        self.window = deque()
        self.total = 0
        self.size = size

    def next(self, val: int) -> float:
        if len(self.window) == self.size:
            head = self.window.popleft()
            self.total -= head
        self.window.append(val)
        self.total += val

        return self.total / len(self.window)


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