AlgoMaster Logo

Sliding Window Median

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Using Sorting

Intuition:

The brute force approach involves recalculating the median every time the sliding window moves. For each new window, we sort the window elements and directly compute the median. This approach is straightforward but inefficient, as sorting each time takes considerable time.

Steps:

  1. Iterate through the nums array, from the start to the end minus the window size k.
  2. For each position, get the subarray of size k and sort it.
  3. Calculate the median:
    • If k is odd, the median is the middle element of the sorted window.
    • If k is even, the median is the average of the two middle elements.
  4. Store the median in the result.

Code:

2. Maintaining Two Heaps (Optimal)

Intuition:

We can use two heaps to maintain the order of the sliding window:

  1. A max-heap to store the smaller half of the numbers.
  2. A min-heap to store the larger half of the numbers.

By always maintaining balance between the two heaps, the median can be derived efficiently:

  • If k is odd, the max-heap will give the median.
  • If k is even, the median is the average of the roots of both heaps.

Steps:

  1. Use a PriorityQueue for both heaps.
  2. Process the elements of the array: add new numbers, remove the old numbers going out of the window.
  3. Ensure the balance between the two heaps every time a insertion or removal is done.
  4. Calculate the median using the top elements of the heaps.

Code: