Sliding Window Median solution explained
Sliding Window Median asks for the median of every block of k consecutive numbers as the block slides one step at a time along a list. The simple fix is to keep the current window sorted and update it with binary search, which costs O(k) per step; the stronger answer keeps the smaller half in a max-heap and the larger half in a min-heap, deletes outgoing numbers lazily, and reaches O(n log n). The hard part is not the idea but the bookkeeping, so test with many repeated values.
By Evin JohnPublished 9 min read
The problem
You get a list of integers and a window size k between 1 and the list's length. Place the window over the first k numbers, report their median, slide it one position right, report again, and continue until the window touches the end. The median of an odd-sized window is its middle value once sorted. For an even-sized window it is the average of the two middle values, which can be a fraction. Return all the medians in order.
nums = [5, 1, 4, 2, 8, 3]
k = 3: [5 1 4] -> 4 [1 4 2] -> 2 [4 2 8] -> 4 [2 8 3] -> 3
answer: [4, 2, 4, 3]
k = 2: [5 1] -> 3 [1 4] -> 2.5 [4 2] -> 3 [2 8] -> 5 [8 3] -> 5.5
answer: [3, 2.5, 3, 5, 5.5]Clarify the output type up front: even windows produce halves, so the answer is usually a list of floating-point numbers. Ask whether values can be very large too, because adding the two middle values can overflow a 32-bit integer in languages that have one. Python and JavaScript are safe here.
Why this one is considered hard
Its cousin, the running median of a stream, only ever adds numbers, and the standard two-heap answer to it is widely practiced. Here numbers also leave, and heaps cannot delete from the middle. The interview is really about what you do with that gap: accept a simpler O(n · k) structure and say so, or design lazy deletion carefully enough that repeated values and window edges do not break it. Either can be a good answer if you are clear about the trade-off.
Baseline: sort every window
def median_sliding_window_slow(nums, k):
medians = []
for i in range(len(nums) - k + 1):
w = sorted(nums[i:i + k])
if k % 2:
medians.append(float(w[k // 2]))
else:
medians.append((w[k // 2 - 1] + w[k // 2]) / 2)
return mediansEach slide changes exactly two numbers, one out and one in, yet this version re-sorts all k of them. Removing that repeated sorting is the whole problem.
Step up: keep the window sorted
Sort the first window once. For every slide, find the outgoing number with binary search and delete it, then find where the incoming number belongs and insert it. The median is read straight from the middle. Binary search finds positions in O(log k), but inserting or deleting in an array shifts elements, so each slide costs O(k). In practice that shift is a fast memory move, and for windows of a few thousand this approach is often quicker than heaps. It is a strong first answer to give, as long as you name its cost.
from bisect import bisect_left, insort
def median_sliding_window_sorted(nums, k):
window = sorted(nums[:k])
medians = []
for i in range(k, len(nums) + 1):
if k % 2:
medians.append(float(window[k // 2]))
else:
medians.append((window[k // 2 - 1] + window[k // 2]) / 2)
if i == len(nums):
break
del window[bisect_left(window, nums[i - k])] # the value leaving
insort(window, nums[i]) # the value entering
return mediansfunction medianSlidingWindow(nums, k) {
const lowerBound = (arr, x) => {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
};
const window = nums.slice(0, k).sort((a, b) => a - b); // numeric sort
const median = () =>
k % 2 ? window[(k - 1) >> 1] : (window[k / 2 - 1] + window[k / 2]) / 2;
const medians = [median()];
for (let i = k; i < nums.length; i++) {
window.splice(lowerBound(window, nums[i - k]), 1);
window.splice(lowerBound(window, nums[i]), 0, nums[i]);
medians.push(median());
}
return medians;
}Note the comparator in the sort call. Without it, JavaScript sorts numbers as strings, so 10 lands before 9 and every median after that is wrong. The lower bound always finds a copy of the outgoing value, because that value is in the window; when it appears several times, any copy is fine to delete.
The two-heap version
Split the window into a lower half and an upper half. The lower half lives in a max-heap so its largest value is on top; the upper half lives in a min-heap so its smallest value is on top. Keep the lower half the same size as the upper half or one bigger. Then the median is the top of the lower heap for odd k, or the average of both tops for even k.
Deleting the outgoing value is the catch, because a heap can only remove its top. So do not delete it yet. Instead, lower the count of live entries on whichever side it belongs to, and remove stale entries only when they reach the top of a heap. To make stale entries easy to spot, store every entry with its index. An entry is stale when its index is before the window's first position. Comparing (value, index) pairs also gives every entry a unique place in the order, which removes the usual confusion when the same value sits in both heaps.
import heapq
def median_sliding_window(nums, k):
low, high = [], [] # low: max-heap of (-value, -index); high: min-heap of (value, index)
low_live = high_live = 0 # entries in each heap that are still inside the window
start = 0 # first index of the current window
def clean_tops():
while low and -low[0][1] < start:
heapq.heappop(low)
while high and high[0][1] < start:
heapq.heappop(high)
medians = []
for i, x in enumerate(nums):
if low and (x, i) < (-low[0][0], -low[0][1]):
heapq.heappush(low, (-x, -i))
low_live += 1
else:
heapq.heappush(high, (x, i))
high_live += 1
if i >= k: # nums[i - k] leaves the window
leaving = (nums[i - k], i - k)
if low and leaving <= (-low[0][0], -low[0][1]):
low_live -= 1
else:
high_live -= 1
start = i - k + 1
clean_tops()
if low_live > high_live + 1: # low may hold one extra, no more
v, j = heapq.heappop(low)
heapq.heappush(high, (-v, -j))
low_live -= 1
high_live += 1
elif high_live > low_live:
v, j = heapq.heappop(high)
heapq.heappush(low, (-v, -j))
high_live -= 1
low_live += 1
clean_tops()
if i >= k - 1:
if k % 2:
medians.append(float(-low[0][0]))
else:
medians.append((-low[0][0] + high[0][0]) / 2)
return mediansThree details keep this correct. First, the side of the outgoing entry is decided by comparing its (value, index) pair with the lower heap's top while that top is still live, before the window start moves. Second, one rebalancing move is always enough, because each slide changes the size difference by at most two. Third, both tops are cleaned after every change, so a move between heaps never carries a stale entry and the median is never read from one. Heaps can hold stale entries for a while, so memory is O(n) in the worst case rather than O(k).
Complexity side by side
| Approach | Time | Extra space | When to pick it |
|---|---|---|---|
| Sort every window | O(n · k log k) | O(k) | Reference only |
| Sorted window with binary search | O(n · k) | O(k) | Small or medium k, or when clarity matters most |
| Two heaps with lazy deletion | O(n log n) | O(n) worst case | Large k, or when asked for better than O(n · k) |
| Balanced tree or sorted multiset | O(n log k) | O(k) | Languages with an ordered multiset built in |
Edge cases
- k = 1: every number is its own median.
- k = n: a single median of the whole list.
- Even k: halves such as 2.5 must survive, so avoid integer division.
- Many repeated values, such as a list of only 0, 1 and 2: the best test for lazy deletion bugs.
- Negative numbers: check that the max-heap negation and the averaging still work.
Typical bugs
- Lazy deletion keyed by value alone, where a stale count for a repeated value removes a live copy from the wrong heap.
- Deciding which heap holds the outgoing value after the window start has moved, when the top may already be stale.
- Reading the median before cleaning the tops.
- Sorting numbers in JavaScript without a numeric comparator.
- Integer division for even windows, which turns 2.5 into 2.
Walking the interviewer through it
Fictional example
- Candidate
- Sorting every window is n times k log k. Each slide only changes two numbers, so I will keep the window sorted and use binary search to delete the old value and insert the new one.
- Candidate
- That is O(k) per slide because of the array shifts, so O(n times k) overall. For moderate k it is fast and hard to get wrong.
- Interviewer
- Can you beat n times k?
- Candidate
- With two heaps for the lower and upper halves. Heaps cannot delete from the middle, so I would track live counts and drop old entries only when they reach a top. I would store indexes with values so an old entry is easy to recognize.
- Candidate
- That gives n log n. I would test it with lots of repeated values, because that is where lazy deletion usually breaks.
Related problems
For windows that grow and shrink instead of keeping a fixed size, compare Fruit Into Baskets, which limits the number of distinct values, and Max Consecutive Ones III, which limits a budget of zeros. Heaps also drive Top K Frequent Elements. The closest relatives without links here are the running median of a stream (heaps without deletion) and the sliding window maximum (a monotonic queue). From the stack set, Remove K Digits is a good contrast in how much state each step needs.
Where Natively fits in your prep
This problem is long enough that interviewers often care more about your plan than your final code. In a practice round, Natively on a Mac or Windows PC can read the prompt from a screenshot, suggest the sorted window or the two-heap layout, and transcribe how you described the trade-off, so you can check later whether you gave both costs. The AI coding interview helper explains what it does during mock sessions.
Questions people ask
How do you solve Sliding Window Median?
Either keep the current window sorted and use binary search to delete the outgoing value and insert the incoming one, which is O(n times k), or keep the lower half in a max-heap and the upper half in a min-heap with lazy deletion, which is O(n log n).
What is lazy deletion in the two-heap solution?
Heaps cannot remove an element from the middle, so the outgoing value is only marked as gone by adjusting a live count. It is physically removed when it reaches the top of its heap. Storing indexes with values makes old entries easy to recognize.
What is the time complexity of Sliding Window Median?
Sorting each window is O(n times k log k). A sorted window with binary search is O(n times k). Two heaps with lazy deletion are O(n log n), and an ordered multiset gives O(n log k).
How do you return the median for an even window size?
Average the two middle values and keep the result as a floating-point number, since it can end in .5. In languages with fixed-size integers, add them in a wider type to avoid overflow.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
