Sliding Window Median (LeetCode 480): Solution and Explanation

Hard
Array
Hash Table
Sliding Window
Heap

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Sort the first k numbers into window.
  2. Define get_median: for odd k return window[k // 2], for even k return the average of window[k // 2 - 1] and window[k // 2], both as floats.
  3. Record the median of the first window.
  4. For each new index i from k to n - 1, delete the outgoing value nums[i - k] at the position found by bisect_left.
  5. Insert the incoming value nums[i] in sorted position with insort.
  6. 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
  1. The first window sorted is [-1, 1, 3], so the median is 1.
  2. Remove 1 and insert -3: [-3, -1, 3], median -1.
  3. Remove 3 and insert 5: [-3, -1, 5], median -1.
  4. Remove -1 and insert 3: [-3, 3, 5], median 3.
  5. Remove -3 and insert 6: [3, 5, 6], median 5. Then remove 5 and insert 7: [3, 6, 7], median 6.
  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 result

Time and space complexity

Time

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).

Space

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) / 2 with 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 value nums[i - k]. Positions in the sorted window have nothing to do with positions in nums.
  • 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.