Sliding Window Median
Explore how to calculate the median for each sliding window in an integer array using heap data structures. This lesson helps you implement an optimized approach to manage dynamic data streams and understand median computations within moving windows, improving your problem-solving skills for coding interviews.
We'll cover the following...
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 of the actual value will be accepted.
Constraints:
-
knums.length -
nums[i]
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
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
[1.0, 1.0, 1.0, 1.0]
[1.5, 1.5, 1.5, 1.5]
[1.0, 1.0, 1.0, 1.0, 1.0]
[1.5, 1.5, 1.5, 1.5, 1.5]
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.
Try it yourself
Implement your solution in the following coding playground.
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 elementspeek(); // return top element without removingpush(val); // insert elementpop(); // remove and return top element}*/export function medianSlidingWindow(nums, k){// Replace this placeholder return statement with your codereturn [];}