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
assert Solution().medianSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3) == [1.0, -1.0, -1.0, 3.0, 5.0, 6.0]
assert Solution().medianSlidingWindow([1, 2, 3, 4, 2, 3, 1, 4, 2], 3) == [2.0, 3.0, 3.0, 3.0, 2.0, 3.0, 2.0]
class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
// indices ordered by (value, index) so duplicates are distinct; lo holds the smaller half (size ceil(k/2))
Comparator<Integer> cmp = (a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : a - b;
TreeSet<Integer> lo = new TreeSet<>(cmp), hi = new TreeSet<>(cmp);
double[] res = new double[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
if (i >= k && !lo.remove(i - k)) hi.remove(i - k);
lo.add(i);
hi.add(lo.pollLast()); // keep every lo <= every hi
if (hi.size() > lo.size()) lo.add(hi.pollFirst());
if (i >= k - 1)
res[i - k + 1] = k % 2 == 1 ? nums[lo.last()] : ((double) nums[lo.last()] + nums[hi.first()]) / 2;
}
return res;
}
}
func medianSlidingWindow(nums []int, k int) []float64 {
win := append([]int{}, nums[:k]...) // the window, kept sorted
sort.Ints(win)
res := []float64{}
for i := k; ; i++ {
res = append(res, (float64(win[k/2])+float64(win[(k-1)/2]))/2)
if i == len(nums) {
return res
}
j := sort.SearchInts(win, nums[i-k]) // remove the outgoing value
win = append(win[:j], win[j+1:]...)
j = sort.SearchInts(win, nums[i]) // insert the incoming one
win = append(win, 0)
copy(win[j+1:], win[j:])
win[j] = nums[i]
}
}