Practice › Sliding Window
Sliding Window Median
Hard · Sliding Window · Asked at Google, Amazon, Meta, Spotify
For every window of k consecutive elements (from left to right), print the median of the window. k is odd, so the median is the middle element after sorting the window.
Input
First line: n k. Second line: n integers.
Output
n − k + 1 medians, space-separated.
Constraints
- 1 ≤ k ≤ n ≤ 10^5
- k is odd
- −10^9 ≤ a[i] ≤ 10^9
Keep the window in two heaps — a max-heap for the smaller half and a min-heap for the larger half — with lazy deletion for elements that slide out, or keep the window in a balanced BST / sorted list. Each step is O(log k).
Example 1
Input
8 3 1 3 -1 -3 5 3 6 7
Output
1 -1 -1 3 5 6
Example 2
Input
5 1 4 2 5 1 3
Output
4 2 5 1 3
Hints
- Sorting every window costs O(k log k) per step.
- Keep the window sorted and update it incrementally: one value leaves, one enters.
- A multiset (C++), or two heaps with lazy deletion, gives O(log k) per step.
Approach
C++: keep the window in a multiset and an iterator mid at the median; when inserting or erasing, move mid one step left or right depending on which side changed. Python: keep a sorted list and use bisect to remove the leaving value and insert the entering one (O(k) per step, fine here). Java: two TreeMaps of counts (lower half and upper half) kept balanced so the lower half has (k + 1) / 2 elements; its maximum is the median.
Complexity: O(n log k) time (C++/Java) · O(k) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<long long> a(n);
for (auto &x : a) cin >> x;
multiset<long long> win(a.begin(), a.begin() + k);
auto mid = next(win.begin(), k / 2);
string out = to_string(*mid);
for (int i = k; i < n; i++) {
win.insert(a[i]);
if (a[i] < *mid) mid--; // new element went to the left of mid
if (a[i - k] <= *mid) mid++; // the leaving element is on the left (or is mid)
win.erase(win.lower_bound(a[i - k]));
out += " " + to_string(*mid);
}
cout << out << "\n";
return 0;
}Python solution
import sys
from bisect import bisect_left, insort
data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
a = data[2 : 2 + n]
win = sorted(a[:k])
out = [win[k // 2]]
for i in range(k, n):
win.pop(bisect_left(win, a[i - k]))
insort(win, a[i])
out.append(win[k // 2])
print(*out)Java solution
import java.io.*;
import java.util.*;
public class Main {
static TreeMap<Long, Integer> low = new TreeMap<>(), high = new TreeMap<>();
static int lowSize = 0, highSize = 0;
static void add(TreeMap<Long, Integer> m, long x) { m.merge(x, 1, Integer::sum); }
static void remove(TreeMap<Long, Integer> m, long x) {
if (m.merge(x, -1, Integer::sum) == 0) m.remove(x);
}
// keep lowSize == highSize or lowSize == highSize + 1
static void balance() {
while (lowSize > highSize + 1) {
long x = low.lastKey();
remove(low, x);
lowSize--;
add(high, x);
highSize++;
}
while (highSize > lowSize) {
long x = high.firstKey();
remove(high, x);
highSize--;
add(low, x);
lowSize++;
}
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int k = (int) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (lowSize == 0 || a[i] <= low.lastKey()) {
add(low, a[i]);
lowSize++;
} else {
add(high, a[i]);
highSize++;
}
if (i >= k) {
long out = a[i - k];
if (low.containsKey(out) && out <= low.lastKey()) {
remove(low, out);
lowSize--;
} else {
remove(high, out);
highSize--;
}
}
balance();
if (i >= k - 1) {
if (sb.length() > 0) sb.append(' ');
sb.append(low.lastKey());
}
}
System.out.println(sb);
}
}