# 480. Sliding Window Median

## Problem Statement

<br>

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.

&#x20;

**Example 1:**

<pre><code><strong>Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
</strong><strong>Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
</strong><strong>Explanation: 
</strong>Window position                Median
---------------                -----
<strong>[1  3  -1] -3  5  3  6  7        1
</strong><strong> 1 [3  -1  -3] 5  3  6  7       -1
</strong><strong> 1  3 [-1  -3  5] 3  6  7       -1
</strong><strong> 1  3  -1 [-3  5  3] 6  7        3
</strong><strong> 1  3  -1  -3 [5  3  6] 7        5
</strong><strong> 1  3  -1  -3  5 [3  6  7]       6
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [1,2,3,4,2,3,1,4,2], k = 3
</strong><strong>Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
</strong></code></pre>

&#x20;

**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
```

### Links

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

### Video Links

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

### Approach 1:

```
Sliding Window + HEap
```

{% code title="C++" lineNumbers="true" %}

```cpp
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;
    }
};
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coding-9.gitbook.io/untitled/heaps-and-priority-queue/480.-sliding-window-median.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
