Skip to content
BytePatterns

Rolling Window Median

HardTwo Heaps & K-Way Merge#two-heaps#lazy-deletion#sliding-window~45m

Problem

Slide a window of k consecutive values across a list of numbers, one position at a time from left to right, and report the median of every window. When k is even the median is the average of the two middle values. Return the medians as floats. Re-sorting each window from scratch is too slow for long lists.

Examples

Input:  nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output: [1.0, -1.0, -1.0, 3.0, 5.0, 6.0]
Input:  nums = [1, 2, 3, 4], k = 4
Output: [2.5]
Why:    an even window averages its two middle values
Input:  nums = [5, 5, 5], k = 1
Output: [5.0, 5.0, 5.0]
Why:    edge case, a window of one value is its own median

Hints

0 / 3

Stuck on the idea rather than the code? Sliding Window Median covers it.