480. Sliding Window Median

Problem Statement

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.

Example 1:

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:

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]

Constraints:

  • 1 <= k <= nums.length <= 105

  • -231 <= nums[i] <= 231 - 1

Intuition

Approach:

Maintain two heaps to divide the window elements into two almost equal
Parts,

Then take top elements as median

But then, one thing to maintain is balance of the heaps,


One problem may arise, elements to be deleted at bottom of the heap
Maintain them in map to be deleted later, if they arrive at top later

https://leetcode.com/problems/sliding-window-median/description/

https://www.youtube.com/watch?v=NT5Lp5vaMm0&t=373s&ab_channel=LeetCodeLearning

Approach 1:

Sliding Window + HEap
C++
class Solution {
public:
    vector<double> medianSlidingWindow(vector<int>& nums, int k) {
        vector<double> medians;
        int n = nums.size();
        unordered_map<int,int> mp; // for late deletion
        priority_queue<int> maxh; // max heap for lower half
        priority_queue<int, vector<int>, greater<int>> minh; // min heap for upper half
        
        for(int i=0;i<k;i++) {
            maxh.push(nums[i]);
        }
         for(int i=0;i<(k/2);i++) {
            minh.push(maxh.top());
            maxh.pop();
        }
        // always try to main the middle element on the top of maxh heap
        // if we have even elements in both the heaps, median is avg of top of both heaps
        for(int i=k;i<n;i++) {
            if(k&1) { // if k is odd, we will have median on the top of maxheap
                medians.push_back(maxh.top()*1.0);
            }
            else {
                medians.push_back(((double)maxh.top()+(double)minh.top())/2);
            }
            int p=nums[i-k], q=nums[i]; // 
            // we need to remove p and add q;
            // we will delete p when it will come on the top
            // to keep track we will maintain map
            int balance = 0; // keep heaps in balance, for correct ans
            // we decrese balance when remove elements from maxh, so basically if balance<0 it means maxheap has lesser elemets the minheap
            // removing p or adding p to map to delete it later
            if(p<=maxh.top()) { // p is in maxheap
                balance--;
                if(p==maxh.top())
                    maxh.pop();
                else
                    mp[p]++;
            }
            else { // p is min heap
                balance++;
                if(p == minh.top())
                    minh.pop();
                else
                    mp[p]++;
            }
            
            // inserting q to the correct heap
            if(!maxh.empty() and q<=maxh.top()) { // pushing q to maxheap
                maxh.push(q);
                balance++;
            }
            else { // pushing q to minheap
                minh.push(q);
                balance--;
            }
            
            // balancing both the heaps
            if(balance<0) {
                maxh.push(minh.top());
                minh.pop();
            }
            else if(balance>0) {
                minh.push(maxh.top());
                maxh.pop();
            }
            
            // removing top elements if they exist in our map(late deletion)
            while(!maxh.empty() and mp[maxh.top()]) {
                mp[maxh.top()]--;
                maxh.pop();
            }
            while(!minh.empty() and mp[minh.top()]) {
                mp[minh.top()]--;
                minh.pop();
            }
        }


        if(k&1) {
            medians.push_back(maxh.top()*1.0);
        }
        else {
            medians.push_back(((double)maxh.top()+(double)minh.top())/2.0);
        }
        return medians;
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated