Sliding Window Median
Give the middle value of every k numbers in a row as the stretch slides along an array.
Given an array of integers numskkk
Example 1
Output: [1.0, -1.0, -1.0, 3.0, 5.0, 6.0]
Example 2
Output: [2.0, 3.0, 3.0, 3.0, 2.0, 3.0, 2.0]
The Idea
Take the first three numbers of Example 1: 1, 3 and -1. Put in order they read -1, 1, 3, and the one in the middle, 1, is their median. One number is below it and one above. Unlike an average, a single huge number cannot drag the median far away.
Now let the three-number frame move. After 1, 3, -1 it covers 3, -1, -3, then -1, -3, 5, and so on, six positions for eight numbers. A frame of fixed size that moves one place at a time like this is called a sliding window, the same idea as in
The plain way is to sort every window and read its middle. But two of the three numbers stay from one window to the next, and sorting them again is wasted work. Can we keep the window's numbers so that the middle is always at hand, and update them with one number in and one number out?
Split the window into a lower half and an upper half. The median sits right where the halves meet: it is the largest number of the lower half, or for even k
A heap gives exactly that. It keeps one value ready at its top and can add a value or take out its top in a few steps, about the log of how many values it holds, without sorting everything. A max-heap keeps its largest value on top, which suits the lower half. A min-heap keeps its smallest on top, which suits the upper half.
Here numbers also leave, and a heap can only take out its top cheaply. The number leaving may be buried deeper. So we leave it where it is, write it on a note of numbers to remove later, and throw it away once it reaches a top. Look at the picture below.
The window has just moved onto 5, 3, 6, and -3 has left it. In the box labelled "lower half (max-heap)", 5 is on top and 3 sits below it. The dashed -3 is still inside too, because it was not on top when it left. The box "to remove later" records it as one copy of -3.
A number like this -3, still in a heap after it left the window, is called stale. It does no harm. The median is read only from the tops, and the top of the lower half is 5, so the median is 5, as in the box "median = 5". If -3 ever comes up to a top, the note says it no longer belongs, and it is thrown away then. Putting off a removal like this is often called lazy deletion.
Solution Approach
Sorting every window works but is slow. The heaps need four decisions: where a new number goes, how the two halves stay the right size, how a number that left the window is removed, and how the median is read. A sorted set, another option, comes last.
Sorting every window
How slow is the plain way? Each of the n - k + 1 windows copies and sorts k numbers, which takes about k log k steps. With 100,000 numbers and k = 50,000, that is 50,001 sorts of 50,000 numbers each. The two heaps instead do a few steps of about log n work for each move of the window.
Where a new number goes
Which half should a new number join? If the lower half is empty, or the number is at most the top of the lower half, it joins the lower half. Otherwise it joins the upper half. This way every number in the lower half stays at most every number in the upper half.
Java's heap class is PriorityQueue(a, b) -> Integer.compare(b, a)
Keeping the halves balanced
How big should each half be? The lower half holds the same number of values as the upper half, or one more. Then for odd kk
A heap's own size counts the stale numbers still inside it, so the code keeps its own counts of numbers that are really in the window, lowSizehighSize
Removing a number that left
How do we take out a number that may be buried in a heap? The code counts it in a map, toRemove
Next, the code works out which half the number counts against. A number at most the top of the lower half is in the lower half, so lowSizehighSize
Throwing away is a small loop, prunetoRemove
Reading the median
Once the first kkkdoubleintint
Another option: sorted sets
Java's TreeSetnums
Java Solution
The method medianSlidingWindow
- First, create the two heaps:
, alow with the comparatorPriorityQueue for the lower half, and(a, b) -> Integer.compare(b, a) , a plainhigh for the upper half. Also create the mapPriorityQueue , the countstoRemove andlowSize , and the arrayhighSize with one slot per window.result - A loop moves
alongi . Each new number goes tonums , which puts it inadd orlow , raises that half's count, and callshigh .balance - Once
reachesi , the numberk has just left the window, so it goes tonums[i - k] . That method counts it inremove , lowers the count of its half, callstoRemove if it is on top, and callsprune .balance moves one top across whenbalance is two more thanlowSize , or smaller than it, and then callshighSize on the heap it took from.prune takes out tops whileprune still counts them.toRemove- Once
reachesi , the window is full, and the loop writes its median intok - 1 . After the loop, the method returnsresult[i - k + 1] .result
The mainkint
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class SlidingWindowMedian {
private PriorityQueue<Integer> low; // max-heap: the smaller half
private PriorityQueue<Integer> high; // min-heap: the larger half
private Map<Integer, Integer> toRemove; // value -> copies left behind
private int lowSize; // live values in low
private int highSize; // live values in high
public double[] medianSlidingWindow(int[] nums, int k) {
low = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
high = new PriorityQueue<>();
toRemove = new HashMap<>();
lowSize = 0;
highSize = 0;
double[] result = new double[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
add(nums[i]);
if (i >= k) {
remove(nums[i - k]); // the value leaving the window
}
if (i >= k - 1) {
result[i - k + 1] = k % 2 == 1
? low.peek()
: ((double) low.peek() + high.peek()) / 2.0;
}
}
return result;
}
private void add(int num) {
if (low.isEmpty() || num <= low.peek()) {
low.offer(num);
lowSize++;
} else {
high.offer(num);
highSize++;
}
balance();
}
private void remove(int num) {
toRemove.merge(num, 1, Integer::sum); // note it, take it out later
if (num <= low.peek()) {
lowSize--;
if (num == low.peek()) {
prune(low);
}
} else {
highSize--;
if (num == high.peek()) {
prune(high);
}
}
balance();
}
private void balance() {
if (lowSize > highSize + 1) { // low is two ahead
high.offer(low.poll());
lowSize--;
highSize++;
prune(low);
} else if (lowSize < highSize) { // high has more than low
low.offer(high.poll());
lowSize++;
highSize--;
prune(high);
}
}
private void prune(PriorityQueue<Integer> heap) {
while (!heap.isEmpty() && toRemove.getOrDefault(heap.peek(), 0) > 0) {
toRemove.merge(heap.poll(), -1, Integer::sum); // a value that already left
}
}
public static void main(String[] args) {
SlidingWindowMedian s = new SlidingWindowMedian();
int[] ex1 = {1, 3, -1, -3, 5, 3, 6, 7};
System.out.println(Arrays.toString(s.medianSlidingWindow(ex1, 3)));
int[] ex2 = {1, 2, 3, 4, 2, 3, 1, 4, 2};
System.out.println(Arrays.toString(s.medianSlidingWindow(ex2, 3)));
System.out.println(Arrays.toString(s.medianSlidingWindow(ex1, 4)));
System.out.println(Arrays.toString(s.medianSlidingWindow(new int[] {5, 2, 8}, 1)));
System.out.println(Arrays.toString(s.medianSlidingWindow(new int[] {2, 2, 2, 2}, 2)));
int max = Integer.MAX_VALUE;
System.out.println(Arrays.toString(s.medianSlidingWindow(new int[] {max, max}, 2)));
}
}
Running it prints:
[1.0, -1.0, -1.0, 3.0, 5.0, 6.0]
[2.0, 3.0, 3.0, 3.0, 2.0, 3.0, 2.0]
[0.0, 1.0, 1.0, 4.0, 5.5]
[5.0, 2.0, 8.0]
[2.0, 2.0, 2.0]
[2.147483647E9]
The top line gives the six medians of Example 1. Below it, [2.0, 3.0, 3.0, 3.0, 2.0, 3.0, 2.0][0.0, 1.0, 1.0, 4.0, 5.5]
With k = 1[5.0, 2.0, 8.0][2, 2, 2, 2]toRemove
The last line, [2.147483647E9]doubleint
Complexity
The work is a few heap steps for each move of the window, plus throwing away the stale numbers once they reach a top.
- Time: O(n log n), because each of the n moves of the window makes a few heap steps that cost about log n each. A call to
oradd moves at most one top between the halves, and each number is thrown away at most once.remove - Space: O(n), because stale numbers can pile up in a heap and in
, besides the n - k + 1 medians intoRemove . For the numbers 0 to 999 in order with k = 3, each leaving number is the smallest and never reaches the top ofresult , solow ends up holding 999 values.low