The median of a list of numbers is its middle value once the list is sorted. When the list has an even length, it is the average of the two middle values.
Take an integer array nums and a window size k. Slide a window of k neighbouring numbers from the left end of nums to the right end, one position at a time. Return the median of every window, in order. Answers within 0.00001 of the true value are accepted.
Example 1
Input: nums = [2, 7, 4, 9, 3, 5], k = 3 Output: [4.0, 7.0, 4.0, 5.0] Why: the middle of 2 4 7, 4 7 9, 3 4 9, 3 5 9
2 more examples and the constraints
Example 2
Input: nums = [6, 1, 4, 3], k = 2 Output: [3.5, 2.5, 3.5] Why: even windows average their two numbers
Example 3
Input: nums = [8, -2, 5, 1], k = 4 Output: [3.0] Why: one window; (1 + 5) / 2 = 3
Constraints
- 1 ≤ k ≤ length of nums ≤ 100,000
- Every nums[i] fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort every windowO(n·k log k)
- Keep the window sortedO(n·k)
- Two heaps, lazy deletionO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 100,000 and k = 50,000 | Verdict |
|---|---|---|---|
| Sort every window | O(n·k log k) | Mention it, then move on | |
| Keep the window sorted | O(n·k) | Passes; shifting is the cost | |
| Two heaps, lazy deletion | O(n log n) | Best; log time per slide |
n = the length of nums, k = the window size.
Edge cases to test
- Window of one. k = 1: every number is its own median.
- Window is the whole array. k = n gives exactly one median.
- Overflow. 2,147,483,647 + 2,147,483,647 does not fit in 32 bits. Add in 64 bits or as doubles before halving.
- Repeated values. Deleting a 2 may remove any copy of 2; the dead count per value handles that.
- Even k. The median can end in .5, so return decimals, not integers.
Common mistakes
- Adding the two middle values as 32-bit integers, which overflows near the limits.
- Balancing the heaps by their raw lengths, which still count dead numbers.
- Removing from a heap by searching it, which is O(k) per slide and loses the gain.
How to talk through it
- 1Clarify. Even k averages two values? Can numbers repeat? Are they full 32-bit integers?
- 2Give the brute force. Sort every window: O(n·k log k). Say that neighbouring windows share k − 1 numbers.
- 3Name the structure. Two heaps keep the median on their tops. The only problem is deletion, so make it lazy.
- 4Code it carefully. Add, remove, balance, read: keep live sizes and prune after every pop.
- 5Test out loud. Run k = 1, an even k, repeats, and the largest values.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?