Skip to content

Sliding Window Median

HardHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

A window of size k slides across nums from left to right, one step at a time. For every position of the window, report the median of the k numbers inside it. The median is the middle value of the sorted window, or the average of the two middle values when k is even.

nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3  →  [1, -1, -1, 3, 5, 6]
nums = [1, 4, 2, 3],               k = 4  →  [2.5]

The first window is [1, 3, -1], whose sorted middle is 1. Answers within 10^-5 of the true value are accepted.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1