##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/480.html

# 480. Sliding Window Median

Hard

## Description

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.

## Solution

### Solution 1 - Two heaps

Use two priority queues to store the smaller half elements and the larger half elements respectively. The first priority queue priorityQueue1 stores the smaller half elements and the largest element is polled first. The second priority queue priorityQueue2 stores the larger half elements and the smallest element is polled first. If there are odd number of elements, then priorityQueue1 stores one more element than priorityQueue2.

The median is calculated in a straightforward way. If k is odd, then peek one element from priorityQueue1, which is the median. If k is even, then peek one element from each queue priorityQueue1 and priorityQueue2 respectively and calculate the mean of the two peeked elements, which is the median.

Since this problem requires calculating the median array for each window, polling elements and offering elements frequently is not efficient. A better way is to use a map to store the invalid elements and the number of occurrences of each invalid element. Each time obtain the previous element in the window that is not in the window any longer and update its number of occurrences in the map. After the previous element and the new element are obtained, check which priority queues the two elements should be in, comparing the two elements with the elements at the top of both priority queues. Then add the new element to the correct priority queue. Then for both priority queues, while the element at the top of each priority queue is in the map of invalid elements, poll them out and update the map. Then calculate the median accordingly.

# Solution 2 - Sorted list-k

We first add the first k arrays of the array to the set. Since multiset has its own sorting function, we can quickly find the iterator mid pointing to the middle number through k/2.

• If k is an odd number, then the number pointed to by mid which is the median;
• if k is an even number, then the average of the number pointed to by mid and the previous number is the median.

When we add a new number to the collection, the multiset will be added to the correct position according to the size of the new number, and then we see that

• if the newly added number is smaller than the number pointed to by the previous mid, then the median must be pulled down , so mid moves forward by one,
• and if the number to be deleted is less than or equal to the number pointed to by mid (note that the equal sign is added here because the number to be deleted may be the number pointed to by mid), then mid moves backward by one.

Then we delete the leftmost number of the sliding window.

• class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
double[] medians = k % 2 == 1 ? medianSlidingWindowOdd(nums, k) : medianSlidingWindowEven(nums, k);
return medians;
}

public double[] medianSlidingWindowOdd(int[] nums, int k) {
PriorityQueue<Integer> priorityQueue1 = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer num1, Integer num2) {
if (num1 < num2)
return 1;
else if (num1 > num2)
return -1;
else
return 0;
}
});
PriorityQueue<Integer> priorityQueue2 = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer num1, Integer num2) {
if (num1 > num2)
return 1;
else if (num1 < num2)
return -1;
else
return 0;
}
});
int length = nums.length - k + 1;
double[] medians = new double[length];
for (int i = 0; i < k; i++)
priorityQueue1.offer(nums[i]);
for (int i = k / 2; i > 0; i--)
priorityQueue2.offer(priorityQueue1.poll());
medians = priorityQueue1.peek();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 1; i < length; i++) {
int prevNum = nums[i - 1];
int count = map.getOrDefault(prevNum, 0) + 1;
map.put(prevNum, count);
int balance = 0;
if (prevNum <= priorityQueue1.peek())
balance--;
else
balance++;
int newNum = nums[i + k - 1];
if (!priorityQueue1.isEmpty() && newNum <= priorityQueue1.peek()) {
priorityQueue1.offer(newNum);
balance++;
} else {
priorityQueue2.offer(newNum);
balance--;
}
if (balance < 0) {
priorityQueue1.offer(priorityQueue2.poll());
balance++;
}
if (balance > 0) {
priorityQueue2.offer(priorityQueue1.poll());
balance--;
}
while (!priorityQueue1.isEmpty() && map.containsKey(priorityQueue1.peek())) {
int pollNum = priorityQueue1.poll();
int newCount = map.get(pollNum) - 1;
if (newCount > 0)
map.put(pollNum, newCount);
else
map.remove(pollNum);
}
while (!priorityQueue2.isEmpty() && map.containsKey(priorityQueue2.peek())) {
int pollNum = priorityQueue2.poll();
int newCount = map.get(pollNum) - 1;
if (newCount > 0)
map.put(pollNum, newCount);
else
map.remove(pollNum);
}
medians[i] = priorityQueue1.peek();
}
return medians;
}

public double[] medianSlidingWindowEven(int[] nums, int k) {
PriorityQueue<Integer> priorityQueue1 = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer num1, Integer num2) {
if (num1 < num2)
return 1;
else if (num1 > num2)
return -1;
else
return 0;
}
});
PriorityQueue<Integer> priorityQueue2 = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer num1, Integer num2) {
if (num1 > num2)
return 1;
else if (num1 < num2)
return -1;
else
return 0;
}
});
int length = nums.length - k + 1;
double[] medians = new double[length];
for (int i = 0; i < k; i++)
priorityQueue1.offer(nums[i]);
for (int i = k / 2; i > 0; i--)
priorityQueue2.offer(priorityQueue1.poll());
medians = (priorityQueue1.peek() * 1.0 + priorityQueue2.peek() * 1.0) / 2.0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 1; i < length; i++) {
int prevNum = nums[i - 1];
int count = map.getOrDefault(prevNum, 0) + 1;
map.put(prevNum, count);
int balance = 0;
if (prevNum <= priorityQueue1.peek())
balance--;
else
balance++;
int newNum = nums[i + k - 1];
if (!priorityQueue1.isEmpty() && newNum <= priorityQueue1.peek()) {
priorityQueue1.offer(newNum);
balance++;
} else {
priorityQueue2.offer(newNum);
balance--;
}
if (balance < 0) {
priorityQueue1.offer(priorityQueue2.poll());
balance++;
}
if (balance > 0) {
priorityQueue2.offer(priorityQueue1.poll());
balance--;
}
while (!priorityQueue1.isEmpty() && map.containsKey(priorityQueue1.peek())) {
int pollNum = priorityQueue1.poll();
int newCount = map.get(pollNum) - 1;
if (newCount > 0)
map.put(pollNum, newCount);
else
map.remove(pollNum);
}
while (!priorityQueue2.isEmpty() && map.containsKey(priorityQueue2.peek())) {
int pollNum = priorityQueue2.poll();
int newCount = map.get(pollNum) - 1;
if (newCount > 0)
map.put(pollNum, newCount);
else
map.remove(pollNum);
}
medians[i] = (priorityQueue1.peek() * 1.0 + priorityQueue2.peek() * 1.0) / 2.0;
}
return medians;
}
}

• class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
vector<double> res;
multiset<int> small, large;
for (int i = 0; i < nums.size(); ++i) {
if (i >= k) {
if (small.count(nums[i - k])) small.erase(small.find(nums[i - k]));
else if (large.count(nums[i - k])) large.erase(large.find(nums[i - k]));
}
if (small.size() <= large.size()) {
if (large.empty() || nums[i] <= *large.begin()) small.insert(nums[i]);
else {
small.insert(*large.begin());
large.erase(large.begin());
large.insert(nums[i]);
}
} else {
if (nums[i] >= *small.rbegin()) large.insert(nums[i]);
else {
large.insert(*small.rbegin());
small.erase(--small.end());
small.insert(nums[i]);
}
}
if (i >= (k - 1)) {
if (k % 2) res.push_back(*small.rbegin());
else res.push_back(((double)*small.rbegin() + *large.begin()) / 2);
}
}
return res;
}
};

• '''
>>> nums = [1,3,-1,-3,5,3,6,7]
>>> k = 3
>>> window = sorted(nums[:k])
>>> window
[-1, 1, 3]
>>>
>>> nums[k:] + 
[-3, 5, 3, 6, 7, 0]
>>> zip(nums, nums[k:] + )
<zip object at 0x108f384c0>
>>> list(zip(nums, nums[k:] + ))
[(1, -3), (3, 5), (-1, 3), (-3, 6), (5, 7), (3, 0)]
>>>
>>>
>>> window.remove(1)
>>> window
[-1, 3]

>>> bisect.insort(window, -3)
>>> window
[-3, -1, 3]
'''

'''
>>> nums
[1, 3, -1, -3, 5, 3, 6, 7]
>>>
>>> nums
3
>>> nums[~1]
6
'''
import bisect

class Solution(object):
def medianSlidingWindow(self, nums, k): # this solution is just the natural flow
window = sorted(nums[:k])
medians = []
for a, b in zip(nums, nums[k:] + ): # + to keep the loop running, e.g. k=3 and nums[1,2,3], so it should enter the loop for one time
medians.append((window[k // 2] + window[~(k // 2)]) / 2.)
window.remove(a)
bisect.insort(window, b)
return medians

###########
# Since we are using k-size heap here, the time complexity is O(nlogk) and space complexity is O(logk).
def medianSlidingWindow(nums, k):
small, large = [], []
for i, x in enumerate(nums[:k]):
heapq.heappush(small, (-x,i))
for _ in range(k-(k>>1)):
move(small, large)
ans = [get_med(small, large, k)]
for i, x in enumerate(nums[k:]):
if x >= large:
heapq.heappush(large, (x, i+k))
if nums[i] <= large:
move(large, small)
else:
heapq.heappush(small, (-x, i+k))
if nums[i] >= large:
move(small, large)
while small and small <= i:
heapq.heappop(small)
while large and large <= i:
heapq.heappop(large)
ans.append(get_med(small, large, k))
return ans

def move(h1, h2):
x, i = heapq.heappop(h1)
heapq.heappush(h2, (-x, i))

def get_med(h1, h2, k):
return h2 * 1. if k & 1 else (h2-h1) / 2.