v9.1.1
Menu

Moving Average Filter

easyFREESliding WindowSliding Window, Signal ProcessingCV - DSA

Problem Statement

A Moving Average Filter (also called a box filter) is one of the simplest smoothing techniques in image and signal processing. It replaces each pixel with the average of its neighboring pixels within a window.

Given a 1D signal (list of integers) and a window size k, compute the moving average for each valid position. Return the result as a list of floats rounded to 2 decimal places.

Application in CV

  • Noise reduction in images (applied row-wise or column-wise)
  • Temporal smoothing in video frames
  • Pre-processing before edge detection

Constraints

  • 1≤len(signal)≤100001 \leq len(signal) \leq 10000
  • 1≤k≤len(signal)1 \leq k \leq len(signal)
  • −10000≤signal[i]≤10000-10000 \leq signal[i] \leq 10000

Example

Input
signal = [1, 2, 3, 4, 5], k = 3
Output
[2.0, 3.0, 4.0]
Reasoning
  • Input: signal is a sequence of n=5n = 5 samples, x1,…,x5=1,2,3,4,5x_1, \dots, x_5 = 1, 2, 3, 4, 5, and k =3= 3 is the window width: how many consecutive samples are averaged together.
  • Valid positions: a window only counts if all kk of its samples lie inside the signal, so it can start at sample 1, 2 or 3. That gives n−k+1=5−3+1=3n - k + 1 = 5 - 3 + 1 = 3 outputs.
  • Math: the output at window jj is yj=1k∑i=jj+k−1xiy_j = \frac{1}{k}\sum_{i=j}^{j+k-1} x_i. Here y1=1+2+33=2y_1 = \frac{1+2+3}{3} = 2, y2=2+3+43=3y_2 = \frac{2+3+4}{3} = 3, y3=3+4+53=4y_3 = \frac{3+4+5}{3} = 4.
  • Output: each average is a float rounded to 2 decimal places, giving [2.0, 3.0, 4.0].
  • Notice: the output is k−1=2k - 1 = 2 samples shorter than the input, because the edges are never padded. On a straight line like this one, each smoothed value equals the window's centre sample (2,3,42, 3, 4), so averaging leaves a linear trend unchanged.

Learn this in

More from CV - DSA

solution.py

Test results

Sign in to run your code against the test cases.