Sliding Window Median

Given an integer array nums and an integer k, representing the size of a sliding window that moves from left to right across the array.

For each window position, calculate the median of its elements. The median is the middle value in a sorted array. If k is even, the median is the smaller of the two middle values.

Return an array containing the medians of all the windows.

Example 1:

Input: nums = [1, 4, 2, 3, 5, 2], k = 3

Output: [2, 3, 3, 3]

Explanation:

Window [1, 4, 2] -> sorted [1, 2, 4] -> median is 2

Window [4, 2, 3] -> sorted [2, 3, 4] -> median is 3

Window [2, 3, 5] -> sorted [2, 3, 5] -> median is 3

Window [3, 5, 2] -> sorted [2, 3, 5] -> median is 3

Example 2:

Input: nums = [4, 5, 1, 3, 2, 6], k = 4

Output: [3, 2, 2]

Explanation:

Window [4, 5, 1, 3] -> sorted [1, 3, 4, 5] -> median is 3

Window [5, 1, 3, 2] -> sorted [1, 2, 3, 5] -> median is 2

Window [1, 3, 2, 6] -> sorted [1, 2, 3, 6] -> median is 2

Now Your Turn!

Pick the correct output for the given input

Input: nums = [8, 5, 9, 2], k = 2

(Return an array containing the sliding window medians from left to right)

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= n <= 2*105
  • 1 <= nums[i] <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> Slidingwindowmedian(vector<int>& nums, int k) {
}
};
Test Case

Input:

K
Nums