Implement sliding-window moving average
Company: Meta
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to implement an efficient streaming data structure and manage numerical precision and overflow when computing a sliding-window moving average.
Constraints
- 1 <= k <= 100000
- 0 <= len(values) <= 200000
- -1000000000 <= values[i] <= 1000000000
Examples
Input: (3, [1, 10, 3, 5])
Expected Output: [1.0, 5.5, 4.666666666666667, 6.0]
Explanation: The averages after each insertion are: [1]/1 = 1.0, [1,10]/2 = 5.5, [1,10,3]/3 = 14/3, and then the window slides to [10,3,5] with average 18/3 = 6.0.
Input: (4, [])
Expected Output: []
Explanation: No values are inserted, so there are no next calls and the result is an empty list.
Hints
- Keep the sum of the current window so you do not need to recompute it from scratch after every insertion.
- When the window grows beyond size k, remove the oldest value and subtract it from the running sum.