Sliding Window Median
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^-5of 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Brute force (sort every window) | O(n · k log k) | O(k) |
| Sorted window with binary search | O(n · k) | O(k) |
| Optimal (two heaps with lazy deletion) | O(n log n) | O(n) |
1Brute force (sort every window)
O(n · k log k)n - k + 1 windows, and each one is sorted from scratch in O(k log k).O(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.
- Make an answer array of size n - k + 1.
- For each start i from 0 to n - k: copy nums[i .. i + k - 1] and sort it.
- The median is (w[(k - 1) / 2] + w[k / 2]) / 2, added as doubles so large values do not overflow.
- 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;
}
}class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
n = len(nums)
ans = []
for i in range(n - k + 1):
w = sorted(nums[i:i + k])
ans.append((w[(k - 1) // 2] + w[k // 2]) / 2.0)
return ansclass Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
int n = (int)nums.size();
vector<double> ans;
for (int i = 0; i + k <= n; i++) {
vector<int> w(nums.begin() + i, nums.begin() + i + k);
sort(w.begin(), w.end());
ans.push_back(((double)w[(k - 1) / 2] + w[k / 2]) / 2.0);
}
return ans;
}
};function medianSlidingWindow(nums, k) {
const n = nums.length;
const ans = [];
for (let i = 0; i + k <= n; i++) {
const w = nums.slice(i, i + k).sort((a, b) => a - b);
ans.push((w[Math.floor((k - 1) / 2)] + w[Math.floor(k / 2)]) / 2);
}
return ans;
}2Sorted window with binary search
O(n · k)The binary searches are O(log k), but inserting into or removing from the middle of a list shifts up to k values, once per step.O(k)The sorted list holds the k values of the window.Neighbouring windows differ by one value going out and one coming in. So keep the current window in a sorted list. To slide, find the leaving value by binary search and remove it, then find where the new value belongs and insert it there. The median is read straight from the middle of the list.
- Put the first k values in a list and sort it. Record its median.
- For each i from k to n - 1: remove nums[i - k] at the index binary search finds for it.
- Insert nums[i] at the first index whose value is not smaller than it.
- Record the median of the list, (w[(k - 1) / 2] + w[k / 2]) / 2.
class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
int n = nums.length;
double[] ans = new double[n - k + 1];
List<Integer> w = new ArrayList<>();
for (int i = 0; i < k; i++) w.add(nums[i]);
Collections.sort(w);
ans[0] = median(w, k);
for (int i = k; i < n; i++) {
w.remove(lowerBound(w, nums[i - k]));
w.add(lowerBound(w, nums[i]), nums[i]);
ans[i - k + 1] = median(w, k);
}
return ans;
}
private int lowerBound(List<Integer> w, int x) {
int lo = 0, hi = w.size();
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (w.get(mid) < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
private double median(List<Integer> w, int k) {
return ((double) w.get((k - 1) / 2) + w.get(k / 2)) / 2.0;
}
}class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
n = len(nums)
ans = []
w = sorted(nums[:k])
ans.append(self.median(w, k))
for i in range(k, n):
w.pop(self.lower_bound(w, nums[i - k]))
w.insert(self.lower_bound(w, nums[i]), nums[i])
ans.append(self.median(w, k))
return ans
def lower_bound(self, w: List[int], x: int) -> int:
lo, hi = 0, len(w)
while lo < hi:
mid = (lo + hi) // 2
if w[mid] < x:
lo = mid + 1
else:
hi = mid
return lo
def median(self, w: List[int], k: int) -> float:
return (w[(k - 1) // 2] + w[k // 2]) / 2.0class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
int n = (int)nums.size();
vector<double> ans;
vector<int> w(nums.begin(), nums.begin() + k);
sort(w.begin(), w.end());
ans.push_back(median(w, k));
for (int i = k; i < n; i++) {
w.erase(w.begin() + lowerBound(w, nums[i - k]));
w.insert(w.begin() + lowerBound(w, nums[i]), nums[i]);
ans.push_back(median(w, k));
}
return ans;
}
private:
int lowerBound(const vector<int>& w, int x) {
int lo = 0, hi = (int)w.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (w[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
double median(const vector<int>& w, int k) {
return ((double)w[(k - 1) / 2] + w[k / 2]) / 2.0;
}
};function medianSlidingWindow(nums, k) {
const n = nums.length;
const ans = [];
const w = nums.slice(0, k);
w.sort((a, b) => a - b);
ans.push(median(w, k));
for (let i = k; i < n; i++) {
w.splice(lowerBound(w, nums[i - k]), 1);
w.splice(lowerBound(w, nums[i]), 0, nums[i]);
ans.push(median(w, k));
}
return ans;
}
function lowerBound(w, x) {
let lo = 0, hi = w.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (w[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
function median(w, k) {
return (w[Math.floor((k - 1) / 2)] + w[Math.floor(k / 2)]) / 2;
}3Optimal (two heaps with lazy deletion)
O(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.O(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.
- Keep lowSize and highSize, the counts of values in each heap that are still in the window.
- add(x): if low is empty or x <= low's top, push x into low, else into high. Then rebalance.
- 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.
- 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.
- prune(heap): while the top is in delayed, pop it and decrease its count.
- 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;
}
}class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
self.low, self.high = [], [] # low keeps negated values, so it acts as a max-heap
self.delayed = {}
self.low_size = self.high_size = 0
ans = []
for i in range(len(nums)):
self.add(nums[i])
if i >= k:
self.remove(nums[i - k])
if i >= k - 1:
ans.append(self.median(k))
return ans
def add(self, x: int) -> None:
if not self.low or x <= -self.low[0]:
heapq.heappush(self.low, -x)
self.low_size += 1
else:
heapq.heappush(self.high, x)
self.high_size += 1
self.rebalance()
def remove(self, x: int) -> None:
self.delayed[x] = self.delayed.get(x, 0) + 1
if x <= -self.low[0]:
self.low_size -= 1
if x == -self.low[0]:
self.prune(self.low, -1)
else:
self.high_size -= 1
if x == self.high[0]:
self.prune(self.high, 1)
self.rebalance()
def rebalance(self) -> None:
if self.low_size > self.high_size + 1:
heapq.heappush(self.high, -heapq.heappop(self.low))
self.low_size -= 1
self.high_size += 1
self.prune(self.low, -1)
elif self.low_size < self.high_size:
heapq.heappush(self.low, -heapq.heappop(self.high))
self.high_size -= 1
self.low_size += 1
self.prune(self.high, 1)
def prune(self, heap: List[int], sign: int) -> None:
# sign turns a stored value back into the real one: -1 for low, 1 for high
while heap and self.delayed.get(sign * heap[0], 0) > 0:
x = sign * heapq.heappop(heap)
self.delayed[x] -= 1
def median(self, k: int) -> float:
if k % 2 == 1:
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2.0class Solution {
priority_queue<int> low;
priority_queue<int, vector<int>, greater<int>> high;
unordered_map<int, int> delayed;
int lowSize = 0, highSize = 0;
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
vector<double> ans;
for (int i = 0; i < (int)nums.size(); i++) {
add(nums[i]);
if (i >= k) remove(nums[i - k]);
if (i >= k - 1) ans.push_back(median(k));
}
return ans;
}
private:
void add(int x) {
if (low.empty() || x <= low.top()) {
low.push(x);
lowSize++;
} else {
high.push(x);
highSize++;
}
rebalance();
}
void remove(int x) {
delayed[x]++;
if (x <= low.top()) {
lowSize--;
if (x == low.top()) prune(low);
} else {
highSize--;
if (x == high.top()) prune(high);
}
rebalance();
}
void rebalance() {
if (lowSize > highSize + 1) {
high.push(low.top());
low.pop();
lowSize--;
highSize++;
prune(low);
} else if (lowSize < highSize) {
low.push(high.top());
high.pop();
highSize--;
lowSize++;
prune(high);
}
}
template <typename Heap>
void prune(Heap& heap) {
while (!heap.empty() && delayed[heap.top()] > 0) {
int x = heap.top();
heap.pop();
delayed[x]--;
}
}
double median(int k) {
if (k % 2 == 1) return low.top();
return ((double)low.top() + high.top()) / 2.0;
}
};function medianSlidingWindow(nums, k) {
const low = new Heap((x, y) => x > y);
const high = new Heap((x, y) => x < y);
const delayed = new Map();
let lowSize = 0, highSize = 0;
const ans = [];
for (let i = 0; i < nums.length; i++) {
add(nums[i]);
if (i >= k) remove(nums[i - k]);
if (i >= k - 1) ans.push(median());
}
return ans;
function add(x) {
if (low.size === 0 || x <= low.peek()) {
low.push(x);
lowSize++;
} else {
high.push(x);
highSize++;
}
rebalance();
}
function remove(x) {
delayed.set(x, (delayed.get(x) || 0) + 1);
if (x <= low.peek()) {
lowSize--;
if (x === low.peek()) prune(low);
} else {
highSize--;
if (x === high.peek()) prune(high);
}
rebalance();
}
function rebalance() {
if (lowSize > highSize + 1) {
high.push(low.pop());
lowSize--;
highSize++;
prune(low);
} else if (lowSize < highSize) {
low.push(high.pop());
highSize--;
lowSize++;
prune(high);
}
}
function prune(heap) {
while (heap.size > 0 && (delayed.get(heap.peek()) || 0) > 0) {
const x = heap.pop();
delayed.set(x, delayed.get(x) - 1);
}
}
function median() {
if (k % 2 === 1) return low.peek();
return (low.peek() + high.peek()) / 2;
}
}
// a binary heap; less(a, b) is true when a should sit above b
class Heap {
constructor(less) {
this.a = [];
this.less = less;
}
get size() {
return this.a.length;
}
peek() {
return this.a[0];
}
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.less(a[l], a[m])) m = l;
if (r < a.length && this.less(a[r], a[m])) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}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.