Rolling Window Medians with Two Heaps and Lazy Removal
Heaps, Sorting & SearchModel answerLast updated
Return the median of every length-k window of an integer array in O(n log k) time, handling duplicates, removals of departing elements, and the even-k convention.
You are given an integer array nums and a window size k. Slide a window of length k from left to right across the array, one position at a time. For each position, report the median of the k values currently in the window. Return all medians in order, as floats.
Details
- Sort the window's values. For odd
k, the median is the middle value. For evenk, it is the average of the two middle values (so a window[1, 2]gives1.5). numsmay contain duplicates and negative numbers. Assume1 <= k <= len(nums).- There are
len(nums) - k + 1windows.
Example 1
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 gives [1, -1, -1, 3, 5, 6].
Example 2
nums = [1, 4, 2, 3], k = 2 gives [2.5, 3.0, 2.5].
What to deliver
- Describe and implement an algorithm that runs in
O(n log k)time. - Explain how it handles repeated values and the removal of the element that leaves the window.
- State the even-
kconvention you use, and analyze the space complexity.
Hints
Hint 1
Sorting every window costs O(n k log k), and keeping one sorted list with insertion and removal still shifts O(k) elements per step. Think about what you actually need: only the middle of the sorted window, not the whole order.
Hint 2
Keep the lower half of the window in a max-heap and the upper half in a min-heap, with sizes that differ by at most one. The median is then read from the heap tops. Standard heaps cannot delete an arbitrary element in O(log k), so consider marking elements as expired and discarding them only when they surface at a top.
Hint 3
If you tag each heap entry with its array index, an entry is expired exactly when its index is below the window start, so no value-keyed counters are needed and duplicates cause no ambiguity. Track the number of live elements per half separately from the physical heap lengths, and rebuild the heaps when they grow beyond about 2k entries to keep memory at O(k).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sorting each window costs O(n·k log k). A sorted list with bisect brings that to O(n·k), because each insertion or removal shifts up to k items. We only need the middle of the window, so we can do better by splitting it into two halves.
Two heaps
lo: a max-heap (values negated) holding the smaller half.hi: a min-heap holding the larger half.
Invariants over the live (in-window) elements:
- Order: every value in
lois <= every value inhi. - Balance:
len_lo - len_hiis 0 or 1, where these are the live counts.
The median is then the top of lo for odd k, or the average of both tops for even k.
Removing the departing element
A binary heap cannot delete an arbitrary item in O(log k), so removal is lazy:
- Each heap entry is a tuple
(value, index). An entry is expired whenindex < window_start. - When an element leaves, we only decrement the live count of the half it sits in. A small array
side[index % k]records which half each in-window element belongs to. - Expired entries are popped only when they reach the top of a heap. We re-clean both tops after every change, so the tops we read are always live.
Tagging entries with the index makes duplicates trivial. Two equal values are different entries, so we never have to decide which copy to remove.
One step of the slide
For each new index i:
- If
i >= k, the element ati-kleaves. Decrement the live count of its half, then clean both tops. - Insert
nums[i]. Ifhiis non-empty andnums[i] >= hi top, push tohi. Otherwise push tolo. This preserves the ordering invariant. - Rebalance with at most one move. The live-count difference can drift to between -2 and 3 after one removal and one insertion, and a single top-to-top move restores it to 0 or 1.
- Clean both tops again, then read the median if
i >= k-1.
Bounding memory
Expired entries buried below the tops are never popped, so the heaps could grow to O(n). Fix: when len(lo) + len(hi) > 2k, filter out expired entries and heapify both lists. Each step adds one physical entry, so this triggers at most once per k steps, and each rebuild costs O(k). That is O(1) amortized per step.
Even k
I return the mean of the two middle values as a float. Some variants ask for the lower median, which is simply -lo[0][0]. State your choice up front. In Java or C++, compute a + (b - a) / 2.0 to avoid integer overflow.
Code
import heapq
def sliding_window_medians(nums, k):
n = len(nums)
if k < 1 or k > n:
return []
lo, hi = [], [] # lo: (-value, idx), hi: (value, idx)
side = [0] * k # side[idx % k]: 0 if entry is in lo, 1 if in hi
cnt = [0, 0] # live counts: cnt[0] for lo, cnt[1] for hi
out = []
def clean(start):
while lo and lo[0][1] < start:
heapq.heappop(lo)
while hi and hi[0][1] < start:
heapq.heappop(hi)
for i in range(n):
start = i - k + 1
if i >= k: # element i-k leaves
cnt[side[i % k]] -= 1
clean(start)
x = nums[i] # element i arrives
if hi and x >= hi[0][0]:
heapq.heappush(hi, (x, i))
side[i % k] = 1
cnt[1] += 1
else:
heapq.heappush(lo, (-x, i))
side[i % k] = 0
cnt[0] += 1
if cnt[0] > cnt[1] + 1: # move top of lo to hi
v, idx = heapq.heappop(lo)
heapq.heappush(hi, (-v, idx))
side[idx % k] = 1
cnt[0] -= 1
cnt[1] += 1
elif cnt[0] < cnt[1]: # move top of hi to lo
v, idx = heapq.heappop(hi)
heapq.heappush(lo, (-v, idx))
side[idx % k] = 0
cnt[1] -= 1
cnt[0] += 1
clean(start)
if len(lo) + len(hi) > 2 * k: # compaction
lo[:] = [e for e in lo if e[1] >= start]
hi[:] = [e for e in hi if e[1] >= start]
heapq.heapify(lo)
heapq.heapify(hi)
if i >= k - 1:
if k % 2:
out.append(float(-lo[0][0]))
else:
out.append((-lo[0][0] + hi[0][0]) / 2)
return out
Why it is correct
- Choosing the destination by comparing with the top of
hikeeps everylovalue <= everyhivalue. - Moving a top across the boundary also preserves that order, since the top of
lois the max of the lower half and the top ofhiis the min of the upper half. - Counts track live elements only, so balancing reflects the true window contents. Cleaning guarantees the tops are the real middle order statistics.
Complexity
- Time: O(n log k) amortized. Each step does a constant number of pushes and pops on heaps of size O(k). Each expired entry is popped at most once, which charges to its insertion. Compaction adds O(1) amortized per step.
- Space: O(k) auxiliary (heaps capped at about 2k entries, plus
side), plus O(n - k + 1) for the output.
Edge cases
k = 1: each window's median is the element itself.k = n: a single window.- All-equal arrays: handled, since entries are distinguished by index.
- Negatives: fine, negation is only used to simulate a max-heap.
Common mistakes
- Deleting by value from a counter while a stale copy of the same value sits in the other heap. This corrupts the balance. Index tagging avoids it.
- Using physical heap lengths for balancing instead of live counts.
- Forgetting to clean the tops after a rebalance, so an expired value is read as the median.
- Never compacting, which leaves memory at O(n) and operations at O(log n).
- Using floor division for even
k, which returns1instead of1.5.
Alternatives and follow-ups
- A Fenwick tree over compressed values gives O(n log n) with a k-th order statistic query. It is simpler to reason about but needs offline coordinate compression.
bisect.insorton a sorted list is O(n·k) in theory, but the memmove is fast in practice and is acceptable for smallk.- Follow-ups: streaming input with unknown values (use an order-statistic tree), or arbitrary percentiles (move the split point away from the middle).