Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs
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:
Implement the function
Rules:
len(series) - k, aligned so the first forecast corresponds to index k in series.np.convolve is allowed, but pandas.Series.rolling is not).Output:
| Argument | Type |
|---|---|
| k | int |
| series | np.ndarray |
| Return Name | Type |
|---|---|
| value | np.ndarray |
Use NumPy only; no pandas rolling.
Runtime must be O(n), not O(nk).
Return NumPy array.
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).
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).
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.