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.

// 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()];
    }
}

Last updated