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 nums and a size k, look at every run of k neighbouring numbers, from left to right, and return the median of each run. The median is the middle value once the numbers are sorted. When k is even there are two middle values, and the median is their average.

Example 1
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]
Example 2
Input: nums = [1, 2, 3, 4, 2, 3, 1, 4, 2], k = 3
Output: [2.0, 3.0, 3.0, 3.0, 2.0, 3.0, 2.0]
Solution

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 Minimum Size Subarray Sum. Each move adds one number on the right and drops one on the left.

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, the average of that number and the smallest of the upper half. So we only ever need the largest of one half and the smallest of the other.

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. Find Median from Data Stream uses the same two halves for numbers that only arrive.

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.

Example 1 with the window on 5, 3, 6. The lower half, a max-heap, holds 5 at the top, 3, and -3, which left the window but is still inside. The upper half, a min-heap, holds 6. The note to remove later says -3, 1 copy. The median is 5, the top of the lower half.

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. On its own it is a min-heap, which is what the upper half needs. For the lower half, the code passes the comparator (a, b) -> Integer.compare(b, a), which reverses the order and so puts the largest value on top.

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 k its top is the middle value, and for even k the two tops are the two middle values.

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, lowSize and highSize. After one number comes in or goes out, one move fixes any imbalance. If the lower half has two more values than the upper half, its top moves to the upper half. If the upper half has more, its top moves to the lower half. A top that moves across is the value nearest the other half, so the order between the halves stays intact.

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, from a value to the number of copies waiting to be thrown away. A count, not a yes or no, matters when a value repeats: Example 2 holds 2 three times.

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 lowSize goes down by one. Otherwise highSize does. If the number is exactly on that top, it is thrown away at once. That keeps the counts right even when equal copies sit in both halves.

Throwing away is a small loop, prune: while the top of a heap has a count above zero in toRemove, take the top out and lower its count. It runs whenever a top may have changed: after a removal on top, and after a balancing move uncovers a new top. So both tops always belong to the window.

Reading the median

Once the first k numbers are in, every move gives one median. For odd k it is the top of the lower half. For even k it is the average of both tops, added as double. Two values near 2,147,483,647, the largest int, would wrap around to a negative total if added as int.

Another option: sorted sets

Java's TreeSet keeps its values sorted and can remove any value in about log k steps, so it removes a leaving number right away, with no note. A set keeps each value once, though, so the two halves would have to store positions in nums, ordered by value and then by position. It runs in O(n log k) and is worth knowing; the code below sticks with heaps.

Java Solution

The method medianSlidingWindow and its helpers work in these steps:

  1. First, create the two heaps: low, a PriorityQueue with the comparator (a, b) -> Integer.compare(b, a) for the lower half, and high, a plain PriorityQueue for the upper half. Also create the map toRemove, the counts lowSize and highSize, and the array result with one slot per window.
  2. A loop moves i along nums. Each new number goes to add, which puts it in low or high, raises that half's count, and calls balance.
  3. Once i reaches k, the number nums[i - k] has just left the window, so it goes to remove. That method counts it in toRemove, lowers the count of its half, calls prune if it is on top, and calls balance.
  4. balance moves one top across when lowSize is two more than highSize, or smaller than it, and then calls prune on the heap it took from.
  5. prune takes out tops while toRemove still counts them.
  6. Once i reaches k - 1, the window is full, and the loop writes its median into result[i - k + 1]. After the loop, the method returns result.

The main method runs both examples, Example 1 again with an even k of 4, a window of one number, four equal numbers, and two copies of the largest int.

Java
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:

Output
[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] shows the three copies of 2 in Example 2 coming and going without upsetting the medians. The third line, [0.0, 1.0, 1.0, 4.0, 5.5], uses windows of four. Its first window, 1, 3, -1, -3, sorts to -3, -1, 1, 3, and the two middle values -1 and 1 average to 0.0. Its last window, 5, 3, 6, 7, gives (5 + 6) / 2 = 5.5.

With k = 1, each number is its own window, so [5.0, 2.0, 8.0] repeats the input. For [2, 2, 2, 2], a leaving 2 and an arriving 2 have the same value, and the count in toRemove makes sure only one copy is thrown away for each 2 that leaves. Every median is 2.0.

The last line, [2.147483647E9], is how Java prints the double 2,147,483,647.0, the correct average of two equal numbers. Adding the two numbers as int instead wraps around to -2, and the median comes out as -1.0.

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 add or remove moves at most one top between the halves, and each number is thrown away at most once.
  • Space: O(n), because stale numbers can pile up in a heap and in toRemove, besides the n - k + 1 medians in result. For the numbers 0 to 999 in order with k = 3, each leaving number is the smallest and never reaches the top of low, so low ends up holding 999 values.