Back

Moving Average from Data Stream

easy

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.
  • double next(int val) returns the moving average of the last size values of the stream.

Test Cases

Copy an input into the main harness and Run to verify
Input
MovingAverage(3), next(1), next(10), next(3), next(5)
Expected Output
1.0, 5.5, 4.66667, 6.0

Explanation: The window holds at most 3 values: [1], [1,10], [1,10,3], then [10,3,5].

Constraints

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

Hints

Hint 1 — click to reveal

A queue naturally models 'oldest value leaves when the window is full'.

Hint 2 — click to reveal

Recomputing the sum each call is wasteful — keep a running total instead.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.