Sliding Window Median

HardTwo Heaps · Sliding Window · Ordered Set🧩 Two HeapsLeetCode #480 ↗Updated

Problem

A window of size k slides one step at a time from the left end of nums to the right end. For every position, report the median of the k numbers inside it (the middle value when sorted, or the average of the two middle values when k is even). Return the medians as a double[]; answers within 10-5 are accepted.
Inputnums = [1,3,-1,-3,5,3,6,7], k = 3Output[1.0,-1.0,-1.0,3.0,5.0,6.0]
Inputnums = [1,2,3,4,2,3,1,4,2], k = 4Output[2.5,2.5,3.0,2.5,2.5,2.5]

1 ≤ k ≤ n ≤ 105  ·  -231 ≤ nums[i] ≤ 231 - 1

Try it yourself

Java
class Solution {
    public double[] medianSlidingWindow(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Split the window into a lower half and an upper half kept in ordered sets; the median lives at their boundary. Sliding is just one insert, one delete and a rebalance — using an ordered set of indices makes deleting the outgoing element O(log k), which plain heaps cannot do.
PatternTwo Heaps

Instinct When you need the middle of a changing collection, or best-of-one-pile fed by another pile, split it into a max-heap low half and a min-heap high half.

Memory hack Small fries in a max-heap, big fish in a min-heap; the median lives on the shoreline between them.

Open the Two Heaps guide →

Approaches

Brute ForceCopy and Sort Every Window

Time O(n · k log k)Space O(k)

For each start i, copy nums[i..i+k-1], sort it and read the middle. Average the two middles in double so huge values cannot overflow.

Java
public double[] medianSlidingWindow(int[] nums, int k) {
    double[] res = new double[nums.length - k + 1];
    for (int i = 0; i + k <= nums.length; i++) {
        int[] w = Arrays.copyOfRange(nums, i, i + k);
        Arrays.sort(w);
        res[i] = k % 2 == 1 ? w[k / 2] : ((double) w[k / 2 - 1] + w[k / 2]) / 2.0;
    }
    return res;
}

Clear baseline; re-sorting k elements per step is wasted work.

At a glance

LevelApproachTimeSpace
Brute ForceCopy and Sort Every WindowO(n · k log k)O(k)
BetterMaintain One Sorted Window ArrayO(n · k)O(k)
OptimalTwo Ordered Sets of Indices (Two-Heap Idea)O(n log k)O(k)
Common pitfalls
  • (a + b) / 2 in int overflows for values near 231 — cast to double first.
  • A TreeSet of values silently drops duplicates; store indices and break ties by index.
  • PriorityQueue.remove(Object) is O(k), quietly turning the heap solution into O(n·k).
Interview tips
  • Build on Find Median from Data Stream (295): same two halves, plus deletions.
  • State the balance invariant (|lo| = |hi| or |hi| + 1) and check it after every slide.
  • Ask about precision — returning doubles with 10-5 tolerance is the norm.
Pattern
Two heaps / two ordered halves → running median or k-th order statistic under inserts and deletes.
My notes saved in this browser