BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges2 of 14 in topic

873. Rolling mean with a cumulative sum

EasyOptimization challenges

Why it matters Moving averages smooth loss curves, metrics dashboards and time series features. The cumulative-sum trick turns O(n w) into O(n).

moving_average(x, w) returns the mean of every full window of length w: out[i] = mean(x[i : i + w]) for i = 0 .. n - w.

Inputs: x is a list or ndarray of floats, shape (n,). w is an int with 1 <= w. If w > n, return an empty float array.

Return an ndarray of floats with shape (max(0, n - w + 1),). No rounding.

The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 20 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.

Functiondef moving_average(x, w)

Example 1

Input: moving_average([1.0, 2.0, 3.0, 4.0, 5.0], 2)

Output: [1.5, 2.5, 3.5, 4.5]

Example 2

Input: x = [4.0, 8.0, 6.0], w = 3

Output: [6.0]

Example 3

Input: x = [1.0, 2.0], w = 5

Output: np.zeros((0,), dtype=float)

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

Build c = [0, x0, x0 + x1, ...] with np.cumsum.

Hint 2

Window sums are c[w:] - c[:-w].

Hint 3

Handle w > n before slicing.

Common mistakes
  • Off-by-one: c[w:] - c[:-w] needs the leading zero.
  • Returning partial windows at the start.
  • Using np.convolve with mode 'same', which pads.
Understand the idea

The sum of x[i : i + w] equals c[i + w] - c[i], where c is the running sum with a leading 0. One cumsum and one subtraction give every window at once. For huge series in float32, the subtraction of two big running sums can lose precision; float64 is fine here.

Shapes and data flow
x: (n,). c: (n + 1,). Output: (n - w + 1,).
Topics
Optimization challenges
Similar questions
  • Count token frequencies fastEasy
  • Batched softmax without the row loopEasy
  • Padding mask from sequence lengthsEasy
  • Confusion matrix in one passEasy
All Optimization challenges problems
Report
873 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
import numpy as np
​
def moving_average(x, w):
x = np.asarray(x, dtype=float)
n = len(x)
out = np.zeros(max(0, n - w + 1))
for i in range(n - w + 1):
out[i] = x[i:i + w].mean()
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS