Search⌘ K
AI Features

Solution: Sliding Window Median

Explore how to efficiently compute the median of each sliding window in an integer array using the heaps pattern. Understand the balanced use of max-heaps and min-heaps, combined with a hash map to optimize removals. This lesson helps you implement an O(n log n) time algorithm to solve median problems in sliding window scenarios while managing the trade-offs of time and space complexity.

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

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive approach

The naive solution is to use nested loops to traverse over the array. The outer loop ranges over the entire array, and the nested loop is used to iterate over windows of kk elements. For each window, we’ll first sort the elements and then compute the median. We’ll append this value to the median list and move the window one step forward.

The above algorithm will have a total time complexity of O(nk+1)O(klogk)O(n - k + 1) \cdot O(k \log k) ...