Search⌘ K
AI Features

Sliding Window Median

Understand how to calculate the median of each sliding window of size k in an integer array by using heaps. Explore solutions that efficiently handle dynamic data with a step-by-step approach and hands-on coding practice.

Statement

Given an integer array, nums, and an integer, k, there is a sliding window of size k, which is moving from the very left to the very right of the array. We can only see the k numbers in the window. Each time the sliding window moves right by one position.

Given this scenario, return the median of the each window. Answers within 10510^{-5} of the actual value will be accepted.

Constraints:

  • 11 \leq k \leq nums.length 103\leq 10^3
  • 231-2^{31} \leq nums[i] 2311\leq 2^{31} - 1

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Sliding Window Median

1.

What should be the output if the following array and value of k are given as input?

nums = [1, 1, 1, 1, 1, 1]

k = 3

A.

[1.0, 1.0, 1.0, 1.0]

B.

[1.5, 1.5, 1.5, 1.5]

C.

[1.0, 1.0, 1.0, 1.0, 1.0]

D.

[1.5, 1.5, 1.5, 1.5, 1.5]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6
7

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > Solution.js
import { MinHeap, MaxHeap } from './Heap.js'
/* The following definition is for MinHeap.
You can use the same methods for MaxHeap.
class MinHeap {
size(); // return number of elements
peek(); // return top element without removing
push(val); // insert element
pop(); // remove and return top element
}
*/
export function medianSlidingWindow(nums, k){
// Replace this placeholder return statement with your code
return [];
}
Sliding Window Median