Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

89. Moving average forecast

easy
GeneralGeneral
senior

Compute a simple moving average (SMA) forecast for a time series, where each forecasted value is the average of the previous (k) observed values. The SMA at time (t) is defined as:

y^t=1k∑i=1kyt−i\hat{y}_t = \frac{1}{k}\sum_{i=1}^{k} y_{t-i}

Requirements

Implement the function

python

Rules:

  • Return a NumPy array of length len(series) - k, aligned so the first forecast corresponds to index k in series.
  • Use NumPy for computation (e.g., cumulative sums or convolution); no pandas.
  • Do not use any prebuilt moving-average helpers (e.g., np.convolve is allowed, but pandas.Series.rolling is not).
  • Keep it efficient: aim for (O(n)) time, not (O(nk)).
  • Output values should be NumPy float array.

Example

python

Output:

python
Input Signature
ArgumentType
kint
seriesnp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Use NumPy only; no pandas rolling.

  • Runtime must be O(n), not O(nk).

  • Return NumPy array.

Hint 1

Start by thinking about what the first forecast should use: it averages series[0:k], and the output length must be len(series) - k (first output aligns to index k).

Hint 2

Avoid an O(n*k) loop by reusing work between windows. A prefix-sum (cumulative sum) lets you get any window sum via subtraction in O(1).

Hint 3

With NumPy: arr = series.astype(float); build csum with a leading 0; then window_sums = csum[k:] - csum[:-k] and divide by k. Return the result as a NumPy array.

Roles
ML Engineer
AI Engineer
Data Scientist
Quantitative Analyst
Companies
GeneralGeneral
Levels
senior
entry
Tags
moving-average
prefix-sum
numpy
time-series
44 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit