All problems
Sliding Window Median
Problem
Return the median of every contiguous window of size k in nums, in left-to-right order.
For each window, sort it and take the middle element, averaging the two middle elements when k is even. Return an empty list when k is non-positive or larger than the list.
Hint
Even windows average the two central elements, so return floats consistently.
Test cases
case 1
in: [[1,3,-1,-3,5,3,6,7],3]
expected: [1,-1,-1,3,5,6]
case 2
in: [[1,2],2]
expected: [1.5]
case 3
in: [[1],1]
expected: [1]
case 4
in: [[5,5,5],2]
expected: [5,5]
case 5
in: [[],3]
expected: []
Starter codePython
def sliding_window_median(nums, k):
# Your code here
pass5 test cases · run your code against them in the editor