Panda Guru LogoPanda
Guru

346. Moving Average from Data Stream

Round 1

Questions:

Question

Given a stream of integers and a window size, implement the MovingAverage class to calculate the moving average of the last size values in the stream.

Methods to Implement:

Examples:

Input: ["MovingAverage", "next", "next", "next", "next"] [[3], [1], [10], [3], [5]] Output: [null, 1.0, 5.5, 4.66667, 6.0] Explanation: MovingAverage ma = new MovingAverage(3); ma.next(1); // returns 1.0 ma.next(10); // returns (1 + 10) / 2 = 5.5 ma.next(3); // returns (1 + 10 + 3) / 3 = 4.66667 ma.next(5); // returns (10 + 3 + 5) / 3 = 6.0
Candidate's Approach

The candidate proposed using a queue to store the last size elements of the stream and maintained a running sum to efficiently calculate the moving average. When the queue exceeded the specified size, the oldest element was removed to ensure only the last size elements were considered.

Interviewer's Feedback

No feedback provided.