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.
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.