Maintain a Windowed Moving Average across Stream Calls

Quick Overview

Maintain a Windowed Moving Average across Stream Calls. Implement MovingAverage(int size) and double next(int val). Each next call appends val and returns the mean of the most recent size values, or of all seen value

Maintain a Windowed Moving Average across Stream Calls

Company: Spotify

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Implement MovingAverage(int size) and double next(int val). Each next call appends val and returns the mean of the most recent size values, or of all seen values while fewer than size have arrived. Preserve the persistent class API. ```cpp class MovingAverage { public: MovingAverage(int size); double next(int val); }; ``` ### Examples ```text MovingAverage(2); next(2) -> 2.0; next(6) -> 4.0; next(4) -> 5.0 MovingAverage(1); next(-3) -> -3.0; next(7) -> 7.0 ``` ### Constraints - Window size is 1 through 1000. - Values lie in [-100000,100000]. - At most 10000 next calls occur.

Overview: Maintain a Windowed Moving Average across Stream Calls. Implement MovingAverage(int size) and double next(int val). Each next call appends val and returns the mean of the most recent size values, or of all seen value

Spotify logo
Spotify
Source window: 0–6 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
1
0

Problem

Implement MovingAverage(int size) and double next(int val). Each next call appends val and returns the mean of the most recent size values, or of all seen values while fewer than size have arrived. Preserve the persistent class API.

class MovingAverage {
public:
    MovingAverage(int size);
    double next(int val);
};

Examples

MovingAverage(2); next(2) -> 2.0; next(6) -> 4.0; next(4) -> 5.0
MovingAverage(1); next(-3) -> -3.0; next(7) -> 7.0

Constraints

  • Window size is 1 through 1000.
  • Values lie in [-100000,100000].
  • At most 10000 next calls occur.