DSA Heaps

Sliding Window Median

Median of every length-k window — two multisets with lazy rebalance.

Hard
Time O(n log k) Space O(k)
LeetCode
7 min read
heaps sliding-window

Problem#

For each length-k window of nums, return its median.

Examples#

  • nums = [1,3,-1,-3,5,3,6,7], k = 3[1,-1,-1,3,5,6]

Constraints#

  • 1 <= k <= nums.length <= 10^5.

Hints#

Hint 1
Two multisets (or two ordered structures) split at the median; both add and delete must keep them balanced.

Approach#

Two multiset<int> halves: lo (lower half) and hi (upper half). Maintain |lo| - |hi| ∈ {0, 1} and max(lo) <= min(hi). Add and remove are O(log k). The median is *lo.rbegin() for odd k, or the average of the boundaries for even k.

Solution#

Sliding Window Median
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
multiset<int> lo, hi;
auto median = [&](){
if (k & 1) return (double)*lo.rbegin();
return ((double)*lo.rbegin() + *hi.begin()) / 2.0;
};
auto add = [&](int x){
if (lo.empty() || x <= *lo.rbegin()) lo.insert(x);
else hi.insert(x);
if (lo.size() > hi.size() + 1) {
hi.insert(*lo.rbegin());
lo.erase(prev(lo.end()));
} else if (hi.size() > lo.size()) {
lo.insert(*hi.begin());
hi.erase(hi.begin());
}
};
auto erase = [&](int x){
if (auto it = lo.find(x); it != lo.end()) lo.erase(it);
else hi.erase(hi.find(x));
if (lo.size() > hi.size() + 1) {
hi.insert(*lo.rbegin());
lo.erase(prev(lo.end()));
} else if (hi.size() < lo.size() - 1 || (lo.size() < hi.size())) {
lo.insert(*hi.begin());
hi.erase(hi.begin());
}
};
vector<double> ans;
for (int i = 0; i < (int)nums.size(); ++i) {
add(nums[i]);
if (i >= k) erase(nums[i - k]);
if (i >= k - 1) ans.push_back(median());
}
return ans;
}
};

Editorial#

A priority queue can’t erase(value) in O(log n) (the value to remove might not be at the top), so we use multiset whose find(x) is O(log n). The two-half invariant is the same as Find Median from a Data Stream; only the deletion path changes. Always rebalance after each add or erase.

Complexity#

  • Time: O(n log k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.