PU Moving Average from Data Steam

Jan 01, 1970

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

For 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

Python Solution:

from collections import deque

class MovingAverage(object):

    def __init__(self, size):
        """
        Initialize your data structure here.
        :type size: int
        """
        self.data = deque(maxlen = size);
        self.sum = 0
        self.size = size

    def next(self, val):
        """
        :type val: int
        :rtype: float
        """
        if self.size == len(self.data):
            self.sum -= self.data.popleft()
        self.data.append(val)
        self.sum += val
        return self.sum / float(len(self.data))


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

C Solution:

typedef struct {
    int *record;
    int size;
    int num;
    int sum;
    int pos;
} MovingAverage;

/** Initialize your data structure here. */
MovingAverage* movingAverageCreate(int size) {
    MovingAverage *obj = malloc(sizeof(MovingAverage));
    obj->record = calloc(size, sizeof(int));
    obj->size = size;
    obj->num = 0;
    obj->sum = 0;
    obj->pos = 0;
    return obj;
}

double movingAverageNext(MovingAverage* obj, int val) {
    obj->sum -= obj->record[obj->pos];
    obj->sum += obj->record[obj->pos] = val;
    if (obj->pos + 1 == obj->size) obj->pos = 0;
    else obj->pos++;
    if (obj->num < obj->size) obj->num++;
    return obj->sum / (double)obj->num;
}

void movingAverageFree(MovingAverage* obj) {
    free(obj->record);
    free(obj);
}

/**
 * Your MovingAverage struct will be instantiated and called as such:
 * struct MovingAverage* obj = movingAverageCreate(size);
 * double param_1 = movingAverageNext(obj, val);
 * movingAverageFree(obj);
 */

Summary:

  • Queue problem

LeetCode: 346. Moving Average from Data Stream