Problem

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.

  • For examples, if arr = [2,3,4], the median is 3.
  • For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.

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

Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Input:
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output:
 [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
Explanation: 
Window position                Median
---------------                -----
[1  3  -1] -3  5  3  6  7        1
 1 [3  -1  -3] 5  3  6  7       -1
 1  3 [-1  -3  5] 3  6  7       -1
 1  3  -1 [-3  5  3] 6  7        3
 1  3  -1  -3 [5  3  6] 7        5
 1  3  -1  -3  5 [3  6  7]       6

Example 2:

1
2
3
4
Input:
nums = [1,2,3,4,2,3,1,4,2], k = 3
Output:
 [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]

Solution

Method 1 – Two Heaps (Max-Heap & Min-Heap)

Intuition

The key idea is to maintain two heaps: a max-heap for the smaller half of the window and a min-heap for the larger half. This allows efficient retrieval of the median at each step. As the window slides, we add the new element and remove the outgoing one, rebalancing the heaps as needed.

Approach

  1. Use a max-heap (small) for the lower half and a min-heap (large) for the upper half of the window.
  2. For each new element:
  • Add it to the appropriate heap.
  • Remove the element that is sliding out of the window.
  • Rebalance the heaps so that their sizes differ by at most one.
  1. The median is:
  • The top of the max-heap if the window size is odd.
  • The average of the tops of both heaps if the window size is even.
  1. Handle lazy deletion for outgoing elements using a hash map or multiset.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
   vector<double> medianSlidingWindow(vector<int>& nums, int k) {
      multiset<int> lo, hi;
      vector<double> ans;
      for (int i = 0; i < nums.size(); ++i) {
        if (lo.empty() || nums[i] <= *lo.rbegin()) lo.insert(nums[i]);
        else hi.insert(nums[i]);
        if (i >= k) {
           if (lo.find(nums[i - k]) != lo.end()) lo.erase(lo.find(nums[i - k]));
           else hi.erase(hi.find(nums[i - k]));
        }
        while (lo.size() > hi.size() + 1) {
           hi.insert(*lo.rbegin());
           lo.erase(prev(lo.end()));
        }
        while (hi.size() > lo.size()) {
           lo.insert(*hi.begin());
           hi.erase(hi.begin());
        }
        if (i >= k - 1) {
           if (k % 2) ans.push_back(*lo.rbegin());
           else ans.push_back(((double)*lo.rbegin() + *hi.begin()) / 2);
        }
      }
      return ans;
   }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
   public double[] medianSlidingWindow(int[] nums, int k) {
      PriorityQueue<Integer> small = new PriorityQueue<>((a, b) -> nums[b] - nums[a]);
      PriorityQueue<Integer> large = new PriorityQueue<>((a, b) -> nums[a] - nums[b]);
      Map<Integer, Integer> delayed = new HashMap<>();
      double[] ans = new double[nums.length - k + 1];

      int si = 0, li = 0;
      for (int i = 0; i < nums.length; ++i) {
        if (small.isEmpty() || nums[i] <= nums[small.peek()]) small.offer(i);
        else large.offer(i);

        if (i >= k) {
           int outIdx = i - k;
           delayed.put(outIdx, delayed.getOrDefault(outIdx, 0) + 1);
           if (!small.isEmpty() && small.peek() == outIdx) small.poll();
           else if (!large.isEmpty() && large.peek() == outIdx) large.poll();
        }

        while (!small.isEmpty() && delayed.getOrDefault(small.peek(), 0) > 0) {
           delayed.put(small.peek(), delayed.get(small.peek()) - 1);
           small.poll();
        }
        while (!large.isEmpty() && delayed.getOrDefault(large.peek(), 0) > 0) {
           delayed.put(large.peek(), delayed.get(large.peek()) - 1);
           large.poll();
        }

        while (small.size() > large.size() + 1) large.offer(small.poll());
        while (large.size() > small.size()) small.offer(large.poll());

        if (i >= k - 1) {
           if (k % 2 == 1) ans[i - k + 1] = nums[small.peek()];
           else ans[i - k + 1] = ((double)nums[small.peek()] + nums[large.peek()]) / 2;
        }
      }
      return ans;
   }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from collections import defaultdict
from heapq import heappush, heappop, heappushpop
from typing import List

class Solution:
   def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
      small, large = [], []
      delayed = defaultdict(int)
      ans = []

      def prune(heap):
        while heap and delayed[heap[0][1] if heap is large else -heap[0][1]]:
           num = heap[0][1] if heap is large else -heap[0][1]
           delayed[num] -= 1
           heappop(heap)

      def balance():
        if len(small) > len(large) + 1:
           heappush(large, (-small[0][0], -small[0][1]))
           heappop(small)
           prune(small)
        elif len(large) > len(small):
           heappush(small, (-large[0][0], -large[0][1]))
           heappop(large)
           prune(large)

      for i, num in enumerate(nums):
        if not small or num <= -small[0][0]:
           heappush(small, (-num, -num))
        else:
           heappush(large, (num, num))
        if i >= k:
           out_num = nums[i - k]
           delayed[out_num] += 1
           if out_num <= -small[0][0]:
              prune(small)
           else:
              prune(large)
        balance()
        if i >= k - 1:
           if k % 2:
              ans.append(float(-small[0][0]))
           else:
              ans.append((-small[0][0] + large[0][0]) / 2)
      return ans

Complexity

  • Time: O(N log K) where N is the length of nums and K is the window size.
  • Space: O(K) for the heaps or multisets.