Your question is Implement a Data Structure or Algorithm. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
Rain processes a stream of transfer amounts and needs the median amount for every consecutive window of size k. Implement an efficient algorithm that supports both adding the newest amount and removing the amount that leaves the window.
Given an integer array amounts and an integer k, return an array containing the median of every contiguous subarray of length k. For an odd-sized window, the median is its middle value after sorting. For an even-sized window, return the arithmetic mean of the two middle values. Results may contain integers or floating-point values.
Your solution should avoid sorting every window independently.
def sliding_window_median(amounts, k):