Compute sliding-window medians
Company: Meta
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in designing and analyzing efficient sliding-window algorithms and data structures for computing running medians, including correct handling of duplicates, deletions, and the convention for defining the median when k is even.
Constraints
- 1 <= k <= nums.length
- Window length k is fixed across all windows.
- Array values may include duplicates and negative numbers.
- Median for even k is the average of the two middle elements (returned as a float).
- Return medians as floating-point values in window order.
Examples
Input: ([1, 3, -1, -3, 5, 3, 6, 7], 3)
Expected Output: [1.0, -1.0, -1.0, 3.0, 5.0, 6.0]
Explanation: Odd k=3: median is the middle element of each sorted window.
Input: ([1, 2, 3, 4], 2)
Expected Output: [1.5, 2.5, 3.5]
Explanation: Even k=2: each median is the average of the two window elements.
Input: ([5], 1)
Expected Output: [5.0]
Explanation: Single-element window; the median is the element itself.
Input: ([2, 2, 2, 2, 2], 3)
Expected Output: [2.0, 2.0, 2.0]
Explanation: All duplicates — removal must target one equal value, not all; every window median is 2.
Input: ([-5, -3, -1, -2, -4], 4)
Expected Output: [-2.5, -2.5]
Explanation: Even k=4 with negatives: window [-5,-3,-1,-2] sorts to [-5,-3,-2,-1], middle two are -3 and -2 → -2.5; next window [-3,-1,-2,-4] sorts to [-4,-3,-2,-1] → -2.5.
Input: ([1, 2, 3, 4, 5, 6], 6)
Expected Output: [3.5]
Explanation: Whole array is a single even-length window; median is average of 3 and 4.
Hints
- Keep the current window in a sorted structure so the median is just the middle element(s) — index k//2 for odd k, average of indices k//2-1 and k//2 for even k.
- When sliding, binary-search for the outgoing element's exact position before removing it; this keeps duplicate handling correct (bisect_left finds the leftmost equal value).
- For a strict O(n log k) bound, use two balanced heaps (a max-heap for the lower half, a min-heap for the upper half) with lazy deletion, rebalancing so their sizes differ by at most one.