# Sliding Window Median

{% embed url="<https://www.lintcode.com/problem/360/>" %}

## Solution 1 (Java)

```java
public class Solution {

    private PriorityQueue<Integer> minHeap, maxHeap;

    /**
     * @param nums: A list of integers
     * @param k: An integer
     * @return: The median of the element inside the window at each moving
     */
    public List<Integer> medianSlidingWindow(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) 
            return res;
        int n = nums.length;
        minHeap = new PriorityQueue<>(n);
        maxHeap = new PriorityQueue<>(n, Collections.reverseOrder());

        for (int i = 0; i < n; i++) {
            if (maxHeap.isEmpty() || nums[i] <= maxHeap.peek()) {
                maxHeap.offer(nums[i]);
            } else {
                minHeap.offer(nums[i]);
            }

            balance();
            if (i - k >= 0) {
                if (nums[i - k] > maxHeap.peek()) {
                    minHeap.remove(nums[i - k]);
                } else {
                    maxHeap.remove(nums[i - k]);
                }
            }

            balance();
            if (i >= k - 1) {
                res.add(maxHeap.peek());
            }
        }
        return res;
    }

    private void balance() {
        while (maxHeap.size() < minHeap.size()) {
            maxHeap.offer(minHeap.poll());
        }
        while (minHeap.size() < maxHeap.size() - 1) {
            minHeap.offer(maxHeap.poll());
        }
    }
}
```

### Notes

* Similar to [Find Median from Data Stream](/algo/heap-and-priority-queue/find-median-from-data-stream.md), we used a minHeap and a maxHeap to maintain the window.
* One more operation needed is to remove the previous number that is outside the current window.


---

# 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://blog.yushunchen.com/algo/heap-and-priority-queue/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.
