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>

  1. Ameya Naik on 2016-5-22

    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();
    }
    }

  2. Ankit Shah on 2016-12-30

    Much more simpler version:


    public class MovingAverageInSlidingWIndow {
    int windowsize;
    Queue queue;
    int sum;

    public MovingAverageInSlidingWIndow(int windowsize) {
    this.windowsize = windowsize;
    this.queue = new LinkedList();
    this.sum = 0;
    }

    // finds moving average after inserting item n into data stream
    private double findMovingAverage(int n) {
    if (queue.size() > windowsize - 1) {
    sum = sum - queue.poll();
    }
    queue.offer(n);
    sum = sum + n;
    return (double) sum / queue.size();
    }

    public static void main(String[] args) {

    int windowsize = 3;
    MovingAverageInSlidingWIndow m = new MovingAverageInSlidingWIndow(windowsize);

    for (int i = 1; i < 20; i++) {
    System.out.println("After Adding " + i + " to the queue: {" + m.queue.toString() + "}; Average is: " + m.findMovingAverage(i));

    }
    }
    }

Leave a comment

*