Grokking Meta Coding Interview

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’:

.....

.....

.....

Like the course? Get enrolled and start learning!
C

chachachoco

· 4 years ago

Could you help explain how heapq._siftup(heap, ind) heapq._siftdown(heap, 0, ind) part works ?

Show 2 replies
T

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?

Show 3 replies
D

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?

Show 2 replies
A

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 .

Show 4 replies
S

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   }
Show 1 reply
F

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.

Show 2 replies
S

Smoke

· 4 years ago

Why not use a sliding window pattern instead?

Show 3 replies
S

Sunil

· 5 years ago

Does Sliding Window Median (hard) solution takes account for duplicates in the input array ?

Show 1 reply
A

Anthony DiFede

· 3 years ago

Show 1 reply