oneby7

Stacks and Queues Monotonic queue

224. Sliding Window Median

Hard

You are given an array of integers nums and an integer k. A window is a block of k neighbouring elements of nums. The first window starts at index 0, the next one at index 1, and so on, up to the window that ends at the last element. So there are nums.length − k + 1 windows.

Return the median of every window, in order from left to right.

The median of a list of numbers is its middle number once the list is sorted. When the list holds an even number of values, it has two middle numbers, and the median is their average, which can end in .5. Equal values count separately, so the median of [2, 9, 2] is 2. The output writes each median with one digit after the point, as in 4.0 or -2.5.

Example 1

Input: nums = [6, 1, 4, 9, 3, 3, 10], k = 4

Output: [5.0,3.5,3.5,6.0]

Explanation: There are four windows. Sorted, they are [1,4,6,9], [1,3,4,9], [3,3,4,9] and [3,3,9,10]. Each holds four values, so each median is the average of the two in the middle: (4 + 6) / 2 = 5, then 3.5, 3.5 and 6.

Example 2

Input: nums = [-2, 5, -7, 0, -7, 3], k = 3

Output: [-2.0,0.0,-7.0,0.0]

Explanation: Each window holds three values, so its median is the middle one once sorted. The third window, [-7,0,-7], sorts to [-7,-7,0]: both copies of −7 count, and the median is −7.

Example 3

Input: nums = [2147483647, 2147483647, -2147483648], k = 2

Output: [2147483647.0,-0.5]

Explanation: The first window holds the largest 32-bit value twice, so its median is that value. The second window holds the largest and the smallest values, and their average is −0.5.

Check your understanding

Work out the answer for this input before you write any code.

nums = [4, 1, 7, 2], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -231 ≤ nums[i] ≤ 231 − 1
  • 1 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.