Python O(1) with rolling sum


  • 0
    A
    class MovingAverage:
        def __init__(self, size):
            """
            Initialize your data structure here.
            :type size: int
            """
            self._queue = collections.deque(maxlen=size)
            self._sum = 0  # rolling sum
    
        def next(self, val):
            if len(self._queue) == self._queue.maxlen:
                self._sum -= self._queue.popleft()
            self._queue.append(val)
            self._sum += val
            return self._sum/len(self._queue)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.