Problem statement

https://leetcode.com/problems/moving-average-from-data-stream/

Solution

Put numbers into queue, until it has maximum size, keep also sum of all elements in queue.

Complexity

Time complexity for next is $O(1)$, space compexity of whole data structure is $O(size)$.

Code

class MovingAverage:
    def __init__(self, size):
        self.queue = deque()
        self.size = size
        self.sum = 0
        
    def next(self, val):
        self.queue.append(val)
        old = 0
        if len(self.queue) > self.size: 
            old = self.queue.popleft()
        self.sum += (val - old)
        return self.sum/len(self.queue)