Moving Average from Data Stream

EasyDesignsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Readings arrive one integer at a time. After each reading, report the average of the most recent size readings — or of all readings so far if fewer than size have arrived. Implement: - MovingAverage(size) sets the window size. - next(val) adds val to the stream and returns the current window average as a floating-point number. Answers within 1e-6 of the exact average are accepted (no rounding needed). Each call should be O(1).

Examples

Input: ["MovingAverage","next","next","next","next"] [[3],[1],[10],[3],[5]]
Output: [null,1.0,5.5,4.666666666666667,6.0]
Averages are 1/1, (1+10)/2 = 5.5, (1+10+3)/3 ≈ 4.6667, then the window drops 1 so (10+3+5)/3 = 6.0.
Input: ["MovingAverage","next","next"] [[1],[-2],[7]]
Output: [null,-2.0,7.0]
With a window of one, each average is just the latest reading.

Constraints

  • 1 <= size <= 1000
  • -10^5 <= val <= 10^5
  • At most 10^4 calls to `next`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems