Skip to content
Decoder

Sliding Window Median

Hard

Problem

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.

Example 1

Input
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output
[1, -1, -1, 3, 5, 6]

Example 2

Input
nums = [1, 4, 2, 3], k = 4
Output
[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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.