Sliding Window Median (LeetCode 480): Solution and Explanation
Slide a window of size k across an array one step at a time and report the median of each window. For an even k the median is the average of the two middle values, so results are returned as floating point numbers.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force sorts every window from scratch, which costs O(k log k) per window and O(n × k log k) overall. That throws away almost all of the work, since consecutive windows share k - 1 elements. Each step only removes one value and adds one value, so the natural improvement is to keep the window in sorted order and update it incrementally.
With the window sorted, the median is an index lookup: the middle element for odd k, or the average of the two middle elements for even k. Removing the outgoing value means finding it with binary search and deleting it, and adding the incoming value means finding its insertion point with binary search and inserting it. Duplicates are fine, since removing any one copy of a value leaves the same multiset.
In Python, a list with bisect_left and insort is the simplest way to do this. The searches are O(log k), but inserting or deleting in the middle of a list shifts elements, so each step costs O(k) in the worst case. Because that shifting is a fast memory move, this approach is quick in practice for the given limits. The fully logarithmic solutions use two heaps with lazy deletion or a balanced tree, and those are worth knowing for the follow-up question.
Approach: Sorted window with binary search updates
- Sort the first k numbers into
window. - Define
get_median: for odd k returnwindow[k // 2], for even k return the average ofwindow[k // 2 - 1]andwindow[k // 2], both as floats. - Record the median of the first window.
- For each new index
ifrom k to n - 1, delete the outgoing valuenums[i - k]at the position found bybisect_left. - Insert the incoming value
nums[i]in sorted position withinsort. - Record the new median and return the list of medians at the end.
Step-by-step example
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
- The first window sorted is [-1, 1, 3], so the median is 1.
- Remove 1 and insert -3: [-3, -1, 3], median -1.
- Remove 3 and insert 5: [-3, -1, 5], median -1.
- Remove -1 and insert 3: [-3, 3, 5], median 3.
- Remove -3 and insert 6: [3, 5, 6], median 5. Then remove 5 and insert 7: [3, 6, 7], median 6.
- The output is [1.0, -1.0, -1.0, 3.0, 5.0, 6.0].
Code: Python, Java, C++
1class Solution:
2 def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
3 from bisect import bisect_left, insort
4
5 window = sorted(nums[:k])
6 result = []
7
8 def get_median():
9 if k % 2 == 1:
10 return float(window[k // 2])
11 return (window[k // 2 - 1] + window[k // 2]) / 2.0
12
13 result.append(get_median())
14
15 for i in range(k, len(nums)):
16 window.pop(bisect_left(window, nums[i - k]))
17 insort(window, nums[i])
18 result.append(get_median())
19
20 return result1class Solution {
2 public double[] medianSlidingWindow(int[] nums, int k) {
3 TreeMap<Integer, Integer> small = new TreeMap<>(Collections.reverseOrder());
4 TreeMap<Integer, Integer> large = new TreeMap<>();
5 int smallSize = 0, largeSize = 0;
6 double[] result = new double[nums.length - k + 1];
7
8 for (int i = 0; i < nums.length; i++) {
9 if (small.isEmpty() || nums[i] <= small.firstKey()) {
10 small.merge(nums[i], 1, Integer::sum);
11 smallSize++;
12 } else {
13 large.merge(nums[i], 1, Integer::sum);
14 largeSize++;
15 }
16
17 // Balance
18 while (smallSize > largeSize + 1) {
19 int val = small.firstKey();
20 large.merge(val, 1, Integer::sum);
21 if (small.merge(val, -1, Integer::sum) == 0) small.remove(val);
22 smallSize--; largeSize++;
23 }
24 while (largeSize > smallSize) {
25 int val = large.firstKey();
26 small.merge(val, 1, Integer::sum);
27 if (large.merge(val, -1, Integer::sum) == 0) large.remove(val);
28 largeSize--; smallSize++;
29 }
30
31 if (i >= k - 1) {
32 if (k % 2 == 1) result[i - k + 1] = small.firstKey();
33 else result[i - k + 1] = ((double) small.firstKey() + large.firstKey()) / 2;
34
35 int toRemove = nums[i - k + 1];
36 if (toRemove <= small.firstKey()) {
37 if (small.merge(toRemove, -1, Integer::sum) == 0) small.remove(toRemove);
38 smallSize--;
39 } else {
40 if (large.merge(toRemove, -1, Integer::sum) == 0) large.remove(toRemove);
41 largeSize--;
42 }
43 }
44 }
45 return result;
46 }
47}1class Solution {
2public:
3 vector<double> medianSlidingWindow(vector<int>& nums, int k) {
4 multiset<int> small, large;
5 vector<double> result;
6
7 auto balance = [&]() {
8 while (small.size() > large.size() + 1) {
9 large.insert(*small.rbegin());
10 small.erase(prev(small.end()));
11 }
12 while (large.size() > small.size()) {
13 small.insert(*large.begin());
14 large.erase(large.begin());
15 }
16 };
17
18 for (int i = 0; i < nums.size(); i++) {
19 if (small.empty() || nums[i] <= *small.rbegin()) {
20 small.insert(nums[i]);
21 } else {
22 large.insert(nums[i]);
23 }
24 balance();
25
26 if (i >= k - 1) {
27 if (k % 2 == 1) result.push_back(*small.rbegin());
28 else result.push_back(((double)*small.rbegin() + *large.begin()) / 2);
29
30 int toRemove = nums[i - k + 1];
31 if (small.count(toRemove)) small.erase(small.find(toRemove));
32 else large.erase(large.find(toRemove));
33 balance();
34 }
35 }
36 return result;
37 }
38};Time and space complexity
O(n × k)
Each of the n - k slides does two O(log k) searches but also shifts up to k list elements on delete and insert. The initial sort adds O(k log k).
O(k)
The sorted window holds k values. The output list of n - k + 1 medians is not counted.
Other approaches
Two heaps with lazy deletion (time O(n log k), space O(n))
Keep a max heap for the lower half and a min heap for the upper half. Instead of removing outgoing values right away, count them in a hash map and discard them when they surface at a heap top, rebalancing by valid sizes. It is the standard O(n log k) answer and extends the running median idea.
Balanced tree or sorted multiset (time O(n log k), space O(k))
Use a multiset in C++ or a sorted list structure and keep an iterator at the median, moving it one step on each insert and erase. It gives true logarithmic updates with less bookkeeping than heaps.
Common mistakes
- Computing
(a + b) / 2with 32-bit integers in Java or C++, which overflows for values near the integer limits. Use doubles or 64-bit math. - Using integer division for even k, which truncates medians like 2.5 to 2.
- Deleting
window[i - k]by position instead of searching for the valuenums[i - k]. Positions in the sorted window have nothing to do with positions innums. - With two heaps, forgetting to rebalance by the count of valid elements rather than the raw heap sizes, which still include lazily deleted values.
Frequently asked questions
What is the time complexity of Sliding Window Median?
With a sorted list it is O(n × k), because inserts and deletes shift elements. With two heaps and lazy deletion, or with a balanced tree, it is O(n log k).
How is this different from Find Median from Data Stream?
The data stream problem only adds numbers, so two heaps work directly. Here values also leave the window, which heaps cannot delete efficiently, so you need lazy deletion or an ordered structure.
Why are the medians returned as doubles?
When k is even the median is the average of two integers, which may be a half value such as 2.5. Returning floats keeps every result exact.