/346. Moving Average from Data Stream

346. Moving Average from Data Stream

Easy
Arrays80.2% acceptance

Implement a class MovingAverage that calculates the moving average of the last k elements from a stream of integers. The class should support the following operations:

1. Initialization with an integer window_size k.

2. A method add_value(val: int) that adds a new integer to the stream and returns the current moving average of the last k elements.

Example 1

Input: window_size = 3 operations = [(1), (10), (5), (7)]

Output: [1.0, 5.5, 5.333333333333333, 7.333333333333333]

Explanation: After each call to add_value: [1], [1,10], [1,10,5], [10,5,7]

Constraints

  • 1 <= window_size <= 10^4
  • -10^5 <= val <= 10^5
  • At most 10^4 calls to add_value
Python (current runtime)

Case 1

Input: window_size = 2 operations = [(-2), (4), (8), (0)]

Expected: [-2.0, 1.0, 6.0, 4.0]

Case 2

Input: window_size = 4 operations = [(3), (6), (9), (12), (15)]

Expected: [3.0, 4.5, 6.0, 7.5, 10.5]

Case 3

Input: window_size = 1 operations = [(100), (-100), (50)]

Expected: [100.0, -100.0, 50.0]