Sliding Window Median

Hard Heaps Advanced

Sliding Window Median is a hard heaps problem solved with the advanced pattern. The best approach, optimal (two heaps with lazy deletion), runs in O(n log n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (sort every window) up.

Problem

You are given an integer array nums and a window size k. A window of k values starts at the left end of the array and slides one position to the right at a time until it reaches the right end, so there are nums.length - k + 1 windows.

For every window, find its median: sort the k values and take the middle one. When k is even there are two middle values, and the median is their average.

Return the medians of all windows, in order, as an array of decimals. Answers within 10^-5 of the true value are accepted.

Examples

Example 1

Input
nums = [4, 1, 7, 3, 8, 5, 2], k = 3
Output
[4.0, 3.0, 7.0, 5.0, 5.0]
Why
The windows are [4, 1, 7], [1, 7, 3], [7, 3, 8], [3, 8, 5] and [8, 5, 2]. Sorted, their middle values are 4, 3, 7, 5 and 5.

Example 2

Input
nums = [5, 2, 2, 9], k = 2
Output
[3.5, 2.0, 5.5]
Why
With an even window the median is the average of the two middle values: (5 + 2) / 2, (2 + 2) / 2 and (2 + 9) / 2.

Example 3

Input
nums = [6], k = 1
Output
[6.0]
Why
A window of one value has that value as its median.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • Answers within 10^-5 of the true median are accepted.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (sort every window)O(n · k log k)O(k)
Sorted window with binary searchO(n · k)O(k)
Optimal (two heaps with lazy deletion)O(n log n)O(n)

1Brute force (sort every window)

TimeO(n · k log k)n - k + 1 windows, and each one is sorted from scratch in O(k log k).
SpaceO(k)One copy of the window at a time, not counting the answer array.

For each start position, copy the k values of the window, sort the copy and read the middle. With k odd the median is the value at index k / 2; with k even it is the average of the values at k / 2 - 1 and k / 2. Both cases are covered by averaging the values at (k - 1) / 2 and k / 2.

  1. Make an answer array of size n - k + 1.
  2. For each start i from 0 to n - k: copy nums[i .. i + k - 1] and sort it.
  3. The median is (w[(k - 1) / 2] + w[k / 2]) / 2, added as doubles so large values do not overflow.
  4. Return the answers.
class Solution {
    public double[] medianSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        double[] ans = new double[n - k + 1];
        for (int i = 0; i + k <= n; i++) {
            int[] w = Arrays.copyOfRange(nums, i, i + k);
            Arrays.sort(w);
            ans[i] = ((double) w[(k - 1) / 2] + w[k / 2]) / 2.0;
        }
        return ans;
    }
}

3Optimal (two heaps with lazy deletion)

TimeO(n log n)Each value is pushed and popped a constant number of times, and every push or pop costs O(log n) because a heap can hold delayed values too.
SpaceO(n)Delayed values can stay in the heaps until they surface, so the heaps and the map can grow to O(n).

Split the window into a lower half in a max-heap (low) and an upper half in a min-heap (high), with low holding the extra value when k is odd. The median is low's top, or the average of both tops. A heap cannot remove a value from the middle, so when a value leaves the window we only write it down in a delayed map and fix the size counters. A delayed value is really thrown away later, when it reaches the top of its heap. Keeping both tops clean means the median is always read from real values.

  1. Keep lowSize and highSize, the counts of values in each heap that are still in the window.
  2. add(x): if low is empty or x <= low's top, push x into low, else into high. Then rebalance.
  3. remove(x): increase delayed[x]. If x <= low's top, it belongs to low: lowSize--, and prune low if x is its top. Otherwise highSize--, and prune high if x is its top. Then rebalance.
  4. rebalance: if lowSize > highSize + 1, move low's top to high; if lowSize < highSize, move high's top to low. Prune the heap that lost its top.
  5. prune(heap): while the top is in delayed, pop it and decrease its count.
  6. For each i: add nums[i]; if i >= k, remove nums[i - k]; if i >= k - 1, record the median.
class Solution {
    private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());
    private final PriorityQueue<Integer> high = new PriorityQueue<>();
    private final Map<Integer, Integer> delayed = new HashMap<>();
    private int lowSize = 0, highSize = 0;

    public double[] medianSlidingWindow(int[] nums, int k) {
        double[] ans = new double[nums.length - k + 1];
        for (int i = 0; i < nums.length; i++) {
            add(nums[i]);
            if (i >= k) remove(nums[i - k]);
            if (i >= k - 1) ans[i - k + 1] = median(k);
        }
        return ans;
    }

    private void add(int x) {
        if (low.isEmpty() || x <= low.peek()) {
            low.offer(x);
            lowSize++;
        } else {
            high.offer(x);
            highSize++;
        }
        rebalance();
    }

    private void remove(int x) {
        delayed.merge(x, 1, Integer::sum);
        if (x <= low.peek()) {
            lowSize--;
            if (x == low.peek()) prune(low);
        } else {
            highSize--;
            if (x == high.peek()) prune(high);
        }
        rebalance();
    }

    private void rebalance() {
        if (lowSize > highSize + 1) {
            high.offer(low.poll());
            lowSize--;
            highSize++;
            prune(low);
        } else if (lowSize < highSize) {
            low.offer(high.poll());
            highSize--;
            lowSize++;
            prune(high);
        }
    }

    private void prune(PriorityQueue<Integer> heap) {
        while (!heap.isEmpty() && delayed.getOrDefault(heap.peek(), 0) > 0) {
            int x = heap.poll();
            delayed.merge(x, -1, Integer::sum);
        }
    }

    private double median(int k) {
        if (k % 2 == 1) return low.peek();
        return ((double) low.peek() + high.peek()) / 2.0;
    }
}

Edge cases to test

  • k = 1: every value is its own median
  • k = nums.length: a single window
  • Even k: average the two middle values
  • Two values near the int limits: adding them as int overflows
  • Many equal values, so the value leaving the window has copies in both halves

Hints

Hint 1

There are n - k + 1 windows. Sorting each one works, but it repeats almost all of its work, because neighbouring windows share k - 1 values.

Hint 2

Keep the window sorted as it slides: each step removes one value and inserts one, both found by binary search.

Hint 3

Split the window into a lower half (a max-heap) and an upper half (a min-heap). The median sits on top. Heaps cannot delete from the middle, so remember the values to delete and throw them away only when they reach a top.

FAQ

What is the best time complexity for Sliding Window Median?

Optimal (two heaps with lazy deletion) runs in O(n log n) time and O(n) extra space. Each value is pushed and popped a constant number of times, and every push or pop costs O(log n) because a heap can hold delayed values too.

Which pattern does Sliding Window Median use?

It is a heaps problem that uses the advanced pattern. Other problems with the same pattern: Find K Pairs with Smallest Sums, Find Median from Data Stream, Trapping Rain Water II.

Is there a brute force solution for Sliding Window Median?

Yes. Brute force (sort every window) takes O(n · k log k) time and O(k) space. For each start position, copy the k values of the window, sort the copy and read the middle.

Which edge cases should I test for Sliding Window Median?

k = 1: every value is its own median; k = nums.length: a single window; Even k: average the two middle values; Two values near the int limits: adding them as int overflows; Many equal values, so the value leaving the window has copies in both halves.