0% completed
Solution: Sliding Window Median
Problem Statement
Given an array of numbers and a number ‘k’, find the median of all the ‘k’ sized sub-arrays (or windows) of the array.
Example 1:
Input: nums=[1, 2, -1, 3, 5], k = 2
Output: [1.5, 0.5, 1.0, 4.0]
Explanation: Lets consider all windows of size ‘2’:
[1, 2, -1, 3, 5] -> median is 1.5
[1, 2, -1, 3, 5] -> median is 0.5
[1, 2, -1, 3, 5] -> median is 1.0
[1, 2, -1, 3, 5] -> median is 4.0
Example 2:
Input: nums=[1, 2, -1, 3, 5], k = 3
Output: [1.0, 2.0, 3.0]
Explanation: Let's consider all windows of size ‘3’:
.....
.....
.....
chachachoco
· 4 years ago
Could you help explain how heapq._siftup(heap, ind) heapq._siftdown(heap, 0, ind) part works ?
Taimur
· 4 years ago
We don't want to use heapify since that would be O(K), but we use heap.index(element) to get the index of the element, and that would take O(K) as well, right? So overall time complexity wise it does not really matter, right?
Dylan Asoh
· 4 years ago
move the element to the end and delete it
heap[ind] = heap[-1] del heap[-1] i don't understand the comment. aren't you moving the element at end to ind, not ind to end?
Adam Sweeney
· 4 years ago
For the C++ example, inheriting from Standard Library containers is generally considered bad practice as the containers do not provide virtual destructors.
You'd be better off creating a simple class that holds a vector and wraps the heap algorithms from .
Shane
· 3 years ago
Without heaps of course.
function find_sliding_window_median(nums, k) { let windowSum = 0, start = 0; for(let i=0; i<nums.length; i++){ windowSum += nums[i] if(i >= k-1){ nums[i-1] = (windowSum / k) windowSum -= nums[start] start++ } } nums.length -=1 return nums }
fumingq
· 3 years ago
Since searching through a heap for the minimum is a O(k) operation, it's easer to just use a linked list and just insertion sort, which is what python's built in list is supposed to be. In fact, if you wanted to implement a binary search for insert and removal, then it would be O(log k) for each update operation leading to an overall time of O(n log k) which is faster than the given solution.
Smoke
· 4 years ago
Why not use a sliding window pattern instead?
Sunil
· 5 years ago
Does Sliding Window Median (hard) solution takes account for duplicates in the input array ?
Anthony DiFede
· 3 years ago
Any feedback on this solution?
https://leetcode.com/problems/sliding-window-median/submissions/888474546/