KatInterview

346. Moving Average from Data Stream

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to implement a MovingAverage class that calculates the moving average of integers from a data stream over a fixed-size sliding window. When a new integer arrives, it's added to the window. If the window is already full (i.e., its size equals the specified size), the oldest integer in the window must be removed to make space for the new one. The moving average is the sum of the integers currently in the window divided by the number of integers in the window.

Solution

Moving Average from Data Stream in Python

class MovingAverage:

    def __init__(self, size: int):
        """
        Initialize your data structure here.
        """
        self.size = size
        # A deque (double-ended queue) is efficient for adding and removing elements from both ends.
        self.window = collections.deque()
        # Use a float for the sum to ensure floating-point division.
        self.sum = 0.0

    def next(self, val: int) -> float:
        # Add the new value to the right side of the deque.
        self.window.append(val)
        # Add the new value to the sum.
        self.sum += val

        # If the deque's size exceeds the specified window size, slide the window.
        if len(self.window) > self.size:
            # Remove the oldest element from the left side of the deque and subtract it from the sum.
            self.sum -= self.window.popleft()
        
        # The moving average is the sum divided by the current number of elements in the window.
        return self.sum / len(self.window)


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

Moving Average from Data Stream in Java

class MovingAverage {
    private Queue<Integer> window; // Queue to store the numbers in the sliding window.
    private int size;              // The maximum size of the window.
    private double sum;            // The sum of numbers currently in the window.

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        // Use LinkedList as it implements the Queue interface.
        this.window = new LinkedList<>();
        this.size = size;
        this.sum = 0;
    }
    
    public double next(int val) {
        // Add the new value to the queue.
        window.add(val);
        // Add the new value to the sum.
        sum += val;
        
        // If the size of the window exceeds the capacity, we need to slide the window.
        if (window.size() > this.size) {
            // Remove the oldest element from the front of the queue and subtract it from the sum.
            // The poll() method retrieves and removes the head of this queue.
            sum -= window.poll();
        }
        
        // The moving average is the sum divided by the current number of elements in the window.
        return sum / window.size();
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new Moving

Moving Average from Data Stream in C++

class MovingAverage {
private:
    std::queue<int> window; // Queue to store the numbers in the sliding window.
    int capacity;           // The maximum size of the window.
    double sum;             // The sum of numbers currently in the window.

public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        this->capacity = size;
        this->sum = 0;
    }
    
    double next(int val) {
        // Add the new value to the queue.
        window.push(val);
        // Add the new value to the sum.
        sum += val;
        
        // If the size of the window exceeds the capacity, we need to slide the window.
        if (window.size() > this->capacity) {
            // Subtract the oldest element (at the front of the queue) from the sum.
            sum -= window.front();
            // Remove the oldest element from the queue.
            window.pop();
        }
        
        // The moving average is the sum divided by the current number of elements in the window.
        return sum / window.size();
    }
};

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage* obj = new MovingAverage(size);
 * double param_1 = obj->next(val);
 */

Moving Average from Data Stream in TypeScript

class MovingAverage {
    private window: number[]; // Array used as a queue to store window elements.
    private size: number;     // The maximum size of the window.
    private sum: number;      // The sum of numbers currently in the window.

    constructor(size: number) {
        this.size = size;
        this.window = [];
        this.sum = 0;
    }

    next(val: number): number {
        // Add the new value to the end of the array (queue).
        this.window.push(val);
        // Add the new value to the sum.
        this.sum += val;

        // If the array length exceeds the window size, we need to slide the window.
        if (this.window.length > this.size) {
            // Remove the first element (oldest) from the array.
            // Note: In JavaScript/TypeScript, array.shift() is an O(n) operation.
            // For the given constraints (size <= 1000), this is acceptable.
            const removedVal = this.window.shift() as number;
            // Subtract the removed value from the sum.
            this.sum -= removedVal;
        }

        // The moving average is the sum divided by the current number of elements.
        return this.sum / this.window.length;
    }
}

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

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.