LeetCode – Moving Average from Data Stream (Java)

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

Java Solution

This problem is solved by using a queue.

public class MovingAverage {
    LinkedList<Integer> queue;
    int size;
    double avg;
 
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.queue = new LinkedList<Integer>();
        this.size = size;
    }
 
    public double next(int val) {
        if(queue.size()<this.size){
            queue.offer(val);
            int sum=0;
            for(int i: queue){
                sum+=i;
            }
            avg = (double)sum/queue.size();
 
            return avg;
        }else{
            int head = queue.poll();
            double minus = (double)head/this.size;
            queue.offer(val);
            double add = (double)val/this.size;
            avg = avg + add - minus;
            return avg;
        }
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Ameya Naik

    We can simply persist the current sum of elements in queue in global variable. Thus, reducing the computation in next() method.


    public class MovingAverage {
    LinkedList queue;
    int size;
    int sum = 0; // holds sum the queue

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
    this.queue = new LinkedList();
    this.size = size;
    }

    public double next(int val) {
    queue.offer(val);
    sum += val;
    if(queue.size()>this.size){
    sum -= queue.poll();
    }

    return (double)sum/queue.size();
    }
    }