SDE & MLE Prep

480. Sliding Window Median

Problem

A window of size k slides over nums from left to right. Return the median of every window (the mean of the two middle values when k is even).

Example: nums = [1,3,-1,-3,5,3,6,7], k = 3 → [1.0,-1.0,-1.0,3.0,5.0,6.0]

Constraints: n ≤ 10⁵.

Maintain the current window sorted: insert the new value and delete the outgoing one with binary search; the median is the middle element(s). Optimal alternative: the two-heap median finder (295) with lazy deletion, or two balanced TreeSets (Java, below), for O(n log k).

Complexity: O(n log k) with balanced trees; O(n·k) with a plain sorted list (fine in practice for Python).

class Solution:
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
        win = sorted(nums[:k])
        res = []
        for i in range(k, len(nums) + 1):
            res.append((win[k // 2] + win[(k - 1) // 2]) / 2)
            if i == len(nums):
                break
            win.pop(bisect.bisect_left(win, nums[i - k]))
            bisect.insort(win, nums[i])
        return res