480. Sliding Window Median
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Two Heaps with Lazy Removal
This problem requires us to find the median of a sliding window of size k as it moves across an array. A naive approach of sorting each window of k elements would be too slow, with a time complexity of O(n * k log k), given the constraints.
Solution
Sliding Window Median in Python
import heapq
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
lo = [] # max-heap, implemented with negative numbers in a min-heap
hi = [] # min-heap
# Initialize heaps with the first window
for i in range(k):
heapq.heappush(lo, -nums[i])
for _ in range(k // 2):
heapq.heappush(hi, -heapq.heappop(lo))
medians = []
to_remove = {}
i = k
while True:
# 1. Get median of the current window
# Prune heaps before calculating median
while lo and -lo[0] in to_remove and to_remove[-lo[0]] > 0:
to_remove[-lo[0]] -= 1
heapq.heappop(lo)
while hi and hi[0] in to_remove and to_remove[hi[0]] > 0:
to_remove[hi[0]] -= 1
heapq.heappop(hi)
if k % 2 == 1:
medians.append(float(-lo[0]))
else:
medians.append((-lo[0] + hi[0]) / 2.0)
if i == len(nums):
break
# 2. Slide window
out_num = nums[i - k]
in_num = nums[i]
balance = 0
# 3. Process outgoing element
to_remove[out_num] = to_remove.get(out_num, 0) + 1
if out_num <= -lo[0]:
balance -= 1
else:
balance += 1
# 4. Process incoming element
if lo and in_num <= -lo[0]:
heapq.heappush(lo, -in_num)
balance += 1
else:
heapq.heappush(hi, in_num)
balance -= 1
# 5. Rebalance heaps
if balance > 0:
heapq.heappush(hi, -heapq.heappop(lo))
if balance < 0:
heapq.heappush(lo, -heapq.heappop(hi))
i += 1
return medians
Sliding Window Median in Java
class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
// lo is a max-heap, hi is a min-heap
PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> hi = new PriorityQueue<>();
double[] result = new double[nums.length - k + 1];
Map<Integer, Integer> to_remove = new HashMap<>();
// Initialize heaps with the first window
for (int i = 0; i < k; i++) {
lo.add(nums[i]);
}
for (int i = 0; i < k / 2; i++) {
hi.add(lo.poll());
}
// The main loop
for (int i = k; ; i++) {
// 1. Get the median of the current window
// The heaps are balanced, and lo.size() >= hi.size()
// Prune the heap tops before getting the median
while (!lo.isEmpty() && to_remove.getOrDefault(lo.peek(), 0) > 0) {
to_remove.put(lo.peek(), to_remove.get(lo.peek()) - 1);
lo.poll();
}
while (!hi.isEmpty() && to_remove.getOrDefault(hi.peek(), 0) > 0) {
to_remove.put(hi.peek(), to_remove.get(hi.peek()) - 1);
hi.poll();
}
result[i - k] = getMedian(lo, hi, k);
if (i == nums.length) {
break;
}
// 2. Slide the window
int out_num = nums[i - k];
int in_num = nums[i];
int balance = 0;
// 3. Process the outgoing element
to_remove.put(out_num, to_remove.getOrDefault(out_num, 0) + 1);
if (out_num <= lo.peek()) {
balance--;
} else {
balance++;
}
// 4. Process the incoming element
if (!lo.isEmpty() && in_num <= lo.peek()) {
lo.add(in_num);
balance++;
} else {
hi.add(in_num);
balance--;
}
// 5. Rebalance the heaps
if (balance > 0) {
hi.add(lo.poll());
}
if (balance < 0) {
lo.add(hi.poll());
}
}
return result;
}
private double getMedian(PriorityQueue<Integer> lo, PriorityQueue<Integer> hi, int k) {
if (k % 2 == 1) {
return (double) lo.peek();
} else {
// Use long to prevent overflow before division
return ((long)lo.peek() + (long)hi.peek()) / 2.0;
}
}
}
Sliding Window Median in C++
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
// Two heaps: lo for the smaller half (max-heap), hi for the larger half (min-heap).
// Using multiset as it provides functionality of heaps and allows efficient element removal.
multiset<int> lo, hi;
vector<double> medians;
for (int i = 0; i < nums.size(); ++i) {
// Add the current element to the heaps.
// We temporarily add to 'lo'.
lo.insert(nums[i]);
// Transfer the largest element from 'lo' to 'hi'.
hi.insert(*lo.rbegin());
lo.erase(prev(lo.end()));
// Balance the heaps: 'lo' should have 0 or 1 more elements than 'hi'.
if (lo.size() < hi.size()) {
lo.insert(*hi.begin());
hi.erase(hi.begin());
}
// If the window is full
if (i >= k - 1) {
// Calculate the median.
if (k % 2 == 1) {
medians.push_back(*lo.rbegin());
} else {
medians.push_back(((double)*lo.rbegin() + (double)*hi.begin()) * 0.5);
}
// Remove the element that is sliding out of the window.
int out_num = nums[i - k + 1];
if (hi.count(out_num)) {
hi.erase(hi.find(out_num));
} else {
lo.erase(lo.find(out_num));
}
// Rebalance after removal.
if (lo.size() < hi.size()) {
lo.insert(*hi.begin());
hi.erase(hi.begin());
}
}
}
return medians;
}
};
Sliding Window Median in TypeScript
class PriorityQueue<T> {
private heap: T[] = [];
private compare: (a: T, b: T) => number;
constructor(compareFn: (a: T, b: T) => number) {
this.compare = compareFn;
}
push(item: T): void {
this.heap.push(item);
this.siftUp(this.heap.length - 1);
}
pop(): T | undefined {
if (this.size() === 0) return undefined;
this.swap(0, this.heap.length - 1);
const popped = this.heap.pop();
this.siftDown(0);
return popped;
}
peek(): T | undefined {
return this.heap[0];
}
size(): number {
return this.heap.length;
}
isEmpty(): boolean {
return this.size() === 0;
}
private siftUp(index: number): void {
let parentIndex = Math.floor((index - 1) / 2);
while (index > 0 && this.compare(this.heap[index], this.heap[parentIndex]) < 0) {
this.swap(index, parentIndex);
index = parentIndex;
parentIndex = Math.floor((index - 1) / 2);
}
}
private siftDown(index: number): void {
while (index < this.heap.length) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let smallestChildIndex = index;
if (leftChildIndex < this.heap.length && this.compare(this.heap[leftChildIndex], this.heap[smallestChildIndex]) < 0) {
smallestChildIndex = leftChildIndex;
}
if (rightChildIndex < this.heap.length && this.compare(this.heap[rightChildIndex], this.heap[smallestChildIndex]) < 0) {
smallestChildIndex = rightChildIndex;
}
if (smallestChildIndex === index) break;
this.swap(index, smallestChildIndex);
index = smallestChildIndex;
}
}
private swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
}
function medianSlidingWindow(nums: number[], k: number): number[] {
const lo = new PriorityQueue<number>((a, b) => b - a); // max-heap
const hi = new PriorityQueue<number>((a, b) => a - b); // min-heap
const result: number[] = [];
const toRemove = new Map<number, number>();
// Initialize heaps with the first window
for (let i = 0; i < k; i++) {
lo.push(nums[i]);
}
for (let i = 0; i < Math.floor(k / 2); i++) {
hi.push(lo.pop()!);
}
for (let i = k; ; i++) {
// 1. Get median of current window
while (!lo.isEmpty() && (toRemove.get(lo.peek()!) || 0) > 0) {
toRemove.set(lo.peek()!, toRemove.get(lo.peek()!)! - 1);
lo.pop();
}
while (!hi.isEmpty() && (toRemove.get(hi.peek()!) || 0) > 0) {
toRemove.set(hi.peek()!, toRemove.get(hi.peek()!)! - 1);
hi.pop();
}
if (k % 2 === 1) {
result.push(lo.peek()!);
} else {
result.push((lo.peek()! + hi.peek()!) / 2);
}
if (i === nums.length) break;
// 2. Slide window
const outNum = nums[i - k];
const inNum = nums[i];
let balance = 0;
// 3. Process outgoing element
toRemove.set(outNum, (toRemove.get(outNum) || 0) + 1);
if (outNum <= lo.peek()!) {
balance--;
} else {
balance++;
}
// 4. Process incoming element
if (!lo.isEmpty() && inNum <= lo.peek()!) {
lo.push(inNum);
balance++;
} else {
hi.push(inNum);
balance--;
}
// 5. Rebalance heaps
if (balance > 0) {
hi.push(lo.pop()!);
}
if (balance < 0) {
lo.push(hi.pop()!);
}
}
return result;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.