Moving Average from Data Stream

EasySliding WindowMath

Description

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

Examples

Input:size = 3, next(1), next(10), next(3), next(5)
Output:[1.0, 5.5, 4.67, 6.0]
Explanation:

Window size is 3. After adding 1: avg = 1/1 = 1.0. After adding 10: avg = (1+10)/2 = 5.5. After adding 3: avg = (1+10+3)/3 = 4.67. After adding 5, window slides: avg = (10+3+5)/3 = 6.0.

Input:size = 1, next(5), next(-3), next(8), next(0)
Output:[5.0, -3.0, 8.0, 0.0]
Explanation:

With window size 1, each moving average is just the current number itself since only one element is considered at a time.

Input:size = 4, next(2), next(4), next(6)
Output:[2.0, 3.0, 4.0]
Explanation:

When there are fewer elements than the window size, the average is computed over all elements seen so far: first 2/1=2.0, then (2+4)/2=3.0, then (2+4+6)/3=4.0.

Constraints

  • 1 ≤ size ≤ 1000
  • -10⁵ ≤ val ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!