Data Structures & AlgorithmsVery hardProduct company OA

Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time limit 2 s. Which approach passes?

  1. A. Keep the window in a Python list and call sorted() after every arrival – O(n·k log k) is fine for 2 seconds
  2. B. Two heaps (max-heap for the lower half, min-heap for the upper half) with lazy deletion of expired values and size rebalancing – O(n log k)
  3. C. Two heaps without any deletion: expired values sink to the bottom and never affect the top
  4. D. A running average of the window, because for latency data the mean equals the median

Correct answer: B. Two heaps (max-heap for the lower half, min-heap for the upper half) with lazy deletion of expired values and size rebalancing – O(n log k)

Re-sorting is about 2·10⁵ × 10⁵·17 ≈ 3·10¹¹ operations. Expired values do not sink in a heap – a large expired value can sit at the top of the min-heap and be reported as the median, so they must be removed: lazily (a 'to delete' counter checked when the value reaches the top, with balance computed from valid sizes) or with an order-statistics structure / two sorted multisets (C++ multiset) – both O(log k) per step. The mean is not the median for skewed data such as latencies.

More Coding Interview Problems questions

Exams that ask this topic