KatInterview

Rolling Window Medians with Two Heaps and Lazy Removal

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchsliding-windowheapmedian

Last 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 even k, it is the average of the two middle values (so a window [1, 2] gives 1.5).
  • nums may contain duplicates and negative numbers. Assume 1 <= k <= len(nums).
  • There are len(nums) - k + 1 windows.

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

  1. Describe and implement an algorithm that runs in O(n log k) time.
  2. Explain how it handles repeated values and the removal of the element that leaves the window.
  3. State the even-k convention 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).