Skip to the code
+50 XP

#396 Median in Every Window

hard

A sensor graph smooths noisy readings by plotting the median of each run of k consecutive readings. Medians ignore single spikes better than averages.

Write windowMedians(nums, k) that returns the median of nums[i..i + k - 1] for every start i from 0 to nums.length - k, in order. For even k, the median is the average of the two middle values. Answers within 1e-5 are accepted.

Example 1

Input: nums = [2,6,-1,-4,5,3,8,7], k = 3
Output: [2,-1,-1,3,5,7]

The first window [2, 6, -1] sorted is [-1, 2, 6], so its median is 2.

Example 2

Input: nums = [4,8,2,6], k = 2
Output: [6,5,4]

Each window of two averages its values: (4 + 8) / 2 = 6, and so on.

Constraints

  • 1 <= k <= nums.length <= 3 * 10^5
  • -10^6 <= nums[i] <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).