Ctrl K

Moving Window Median

Hard
An analyst tracks the price of a product: the array prices holds one price per day. To smooth out spikes, they look at a window of width consecutive days, starting at the first day, and shift it right one day at a time until it reaches the end. For every position of the window they need the **median** of the prices in it. Sort the window's numbers in increasing order: with an odd width the median is the middle number, and with an even width it is the average of the two middle ones. For example, the median of [2, 7, 3] is 3, and the median of [4, 1, 6, 2] is (2 + 4) / 2 = 3. Return the medians of all windows in the order the window moves. Answers within 10⁻⁵ of the exact value are accepted.
Example 1
prices=[5, 1, 4, 8, 2], width=3 → [4, 4, 4]

The windows are [5, 1, 4], [1, 4, 8] and [4, 8, 2]; once sorted, their middle elements are 4, 4 and 4.

Example 2
prices=[3, 9, 6, 6], width=2 → [6.0, 7.5, 6.0]

With an even width, the median is the mean of the two middle numbers: (3 + 9) / 2 = 6, (9 + 6) / 2 = 7.5, (6 + 6) / 2 = 6.

Example 3
prices=[-7], width=1 → [-7]

One window holding one number.

Constraints
  • 1 ≤ width ≤ len(prices) ≤ 10⁵
  • -2³¹ ≤ prices[i] ≤ 2³¹ - 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNarrowest Range Touching Every List HardCheapest Cut With Close Starts HardTop Frequency Window Sums: Large Input HardTop-Frequency Window Sums EasyA Level Stretch of Fence Medium
loading Python…
Input
prices=[5, 1, 4, 8, 2], width=3
Expected
[4, 4, 4]

Run checks the first 3 tests in your browser. Submit checks all 118 tests on the server, hidden ones included.