Problems
Loading...
1 / 1

Moving Median

Time Series
Easy

The moving median is a robust alternative to the moving average for smoothing time series. While the moving average is sensitive to outliers (a single spike can shift the average significantly), the median is unaffected by extreme values. This makes it ideal for signal processing, sensor data cleaning, and financial data where occasional spikes or errors occur.

Given a list of values and a window size, compute the median for each sliding window position.

Algorithm

For each window, sort the values. If the window size is odd, the median is the middle element. If even, it is the average of the two middle elements. The output has length n - window_size + 1.

Loading visualization...

Examples

Input:

values = [1, 3, 5, 7, 9], window_size = 3

Output:

[3.0, 5.0, 7.0]

Window [1,3,5] sorted -> median=3. Window [3,5,7] -> median=5. Window [5,7,9] -> median=7.

Input:

values = [1, 2, 3, 4], window_size = 2

Output:

[1.5, 2.5, 3.5]

Even window size: median of [1,2] = (1+2)/2 = 1.5, median of [2,3] = 2.5, median of [3,4] = 3.5.

Hint 1

For each window starting at position i, extract the slice values[i:i+window_size], sort it, and find the median. Remember that sorted() returns a new list without modifying the original.

Hint 2

For the median: if n is odd, return sorted_window[n//2]. If n is even, return (sorted_window[n//2-1] + sorted_window[n//2]) / 2.

Requirements

  • For each sliding window, sort the values and find the median
  • For odd window size, return the middle element
  • For even window size, return the average of the two middle elements
  • Return a list of floats of length n - window_size + 1

Constraints

  • values has at least window_size elements
  • window_size >= 1
  • Return a list of floats
  • Time limit: 300 ms
Try Similar Problems