Saturday, February 27, 2021

[Indeed Question][LeetCode] Moving Average from Data Stream

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

Implement the MovingAverage class:

  • MovingAverage(int size) Initializes the object with the size of the window size.
  • double next(int val) Returns the moving average of the last size values of the stream.

Example:

Input
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]

Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3


Approach: We can solve this question easily by using a queue. Please look at the implementation to understand the approach.

 

Implementation in C#:

public class MovingAverage 

{

    public MovingAverage(int size) 

    {

        this.windowSize = size;

        this.queue = new Queue<int>();

        this.currSum = 0;

    }

    

    public double Next(int val) 

    {

        this.currSum += val;

        this.queue.Enqueue(val);

        if (this.queue.Count > this.windowSize)

        {

            this.currSum -= this.queue.Dequeue();

        }

        return (double)this.currSum / this.queue.Count;

    }

    

    private int currSum;

    private Queue<int> queue;

    private int windowSize;

}


Complexity: O(1)


No comments:

Post a Comment