> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/priority-queue/sliding-window-median.md).

# Sliding Window Median

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 value.Examples:

`[2,3,4]` , the median is `3`

`[2,3]`, the median is `(2 + 3) / 2 = 2.5`

Given an array nums, 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. Your job is to output the median array for each window in the original array.

For example,\
Given nums = `[1,3,-1,-3,5,3,6,7]`, and k = 3.

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

Therefore, return the median sliding window as `[1,-1,-1,3,5,6]`.

**Note:**\
You may assume `k` is always valid, ie: `k` is always smaller than input array's size for non-empty array.\
Answers within `10^-5` of the actual value will be accepted as correct.<br>

```java
// The problem is similar to running median of a stream
// BUT the core problem lies in how to remove the (i-k)th element
// from PQs when adding the new ith element
// Just like PQ, we can get the min & max from treeSets
// Using pollFirst(), pollLast(), first(), & last()
// We can also remove particular element using remove(x)
class Solution {
    // O(NlogK)
    public double[] medianSlidingWindow(int[] nums, int k) {
        // Storing indices of the window
        // Works as max heap (Integer.compare prevents overflow compared to direct subtraction)
        TreeSet<Integer> left = new TreeSet<>((a, b) -> nums[a] != nums[b] ? Integer.compare(nums[b], nums[a]) : b - a);
        // Works as min heap
        TreeSet<Integer> right = new TreeSet<>((a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : a - b);
        // If we dont use a-b OR b-a in above comparators, then treeset will take 2
        // different indices values as same, just because they might have same value in
        // array(nums)
        double[] res = new double[nums.length - k + 1];

        for (int i = 0; i < k; i++)
            left.add(i);
        balance(left, right);
        res[0] = getMedian(k, nums, left, right);

        int index = 1;
        for (int i = k; i < nums.length; i++) {
            // Removing the (i-k)th element in O(logN)
            if (left.contains(i - k))
                left.remove(i - k);
            else
                right.remove(i - k);
            // Remember right treeset holds the bigger values of set
            right.add(i);
            left.add(right.pollFirst());
            balance(left, right);
            res[index] = getMedian(k, nums, left, right);
            index++;
        }

        return res;
    }

    private void balance(TreeSet<Integer> left, TreeSet<Integer> right) {
        while (left.size() > right.size())
            right.add(left.pollFirst());
    }

    private double getMedian(int k, int[] nums, TreeSet<Integer> left, TreeSet<Integer> right) {
        if (k % 2 == 0)
            return ((double) nums[left.first()] + nums[right.first()]) / 2;
        else
            return (double) nums[right.first()];
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://mayanktyagi3111.gitbook.io/interview-prep/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.
