Similar to the "Sliding Window Maximum" problem, the "Sliding Window Median" interview question involves a window of size k moving across an array. However, instead of the maximum, you must find the median of the k numbers in the window at each step. This "Sliding Window Median coding problem" is significantly harder because the median is the middle element in a sorted list, and maintaining a sorted list while adding and removing elements is computationally expensive.
Companies like Apple, Microsoft, and Meta use this to test a candidate's mastery of advanced data structures. It requires you to balance two priority queues (heaps) or use a balanced BST. It evaluates your ability to handle insertions, deletions, and rebalancing in O(log k) time. This problem is a true test of whether you can optimize complex operations within a sliding window framework.
The "Two Heaps (Priority Queues) and Sliding Window interview pattern" is the standard O(N log K) approach.
Array: [1, 3, -1, -3, 5], k=3
[1, 3, -1]: Sorted is [-1, 1, 3]. Median is 1.[3, -1, -3]: Sorted is [-3, -1, 3]. Median is -1.[-1, -3, 5]: Sorted is [-3, -1, 5]. Median is -1.
Final result: [1, -1, -1].
Maintaining this without full re-sorting is the key challenge.A major pitfall is attempting to re-sort the entire window at every step, which is O(N * K log K). Another common error is failing to handle the removal of elements correctly when they leave the sliding window. Precision errors with floating-point math when calculating the average of two numbers (if k is even) can also occur. Many candidates also forget to keep the two heaps balanced in terms of size.
The "Two Heaps" pattern is a classic for finding the "Median from Data Stream." For the "Sliding Window Median interview question", you just add the deletion logic. Practice the "lazy deletion" technique with a frequency map to handle standard priority queue limitations in languages like C++ or Java.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find X-Sum of All K-Long Subarrays II | Hard | Solve | |
| Divide an Array Into Subarrays With Minimum Cost II | Hard | Solve | |
| Find X-Sum of All K-Long Subarrays I | Easy | Solve | |
| Maximum Erasure Value | Medium | Solve | |
| Minimum Consecutive Cards to Pick Up | Medium | Solve |