Sliding Window Median

Given a list of integers and a window size k, compute the medians of the all the sliding windows.

Example

I: [1,3,-1,-3,5,3,6,7], 4
O: [0.00000,1.00000,1.00000,4.00000,5.50000]

Window position                Median
---------------               -----
[1  3  -1 -3]  5  3  6  7       0.00
 1 [3  -1  -3 5]  3  6  7       1.00
 1  3 [-1  -3  5 3]  6  7       1.00
 1  3  -1 [-3  5  3 6]  7       4.00
 1  3  -1  -3 [5  3  6 7]       5.50 

Analysis

To maintain a sliding window, we need to support deletion. A balanced binary search tree is the easiest tool to use.

Code

Time Complexity

For each window, adding is O(logk) finding median is O(logk) deleting is O(logk).

Because SortedListarrow-up-right is sorted, it supports efficient lookups by value or by index. When accessing values by index, the SortedListarrow-up-right can be used as an order statistic treearrow-up-right.

Last updated