Data Structures & AlgorithmsHardProduct Company SDE · heap round

Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?

  1. A. A single sorted array with insertion by shifting
  2. B. A plain queue with linear search for the median
  3. C. Two heaps (a max-heap for the lower half and a min-heap for the upper half) with lazy deletion
  4. D. A hash map from value to count with the median read from the keys

Correct answer: C. Two heaps (a max-heap for the lower half and a min-heap for the upper half) with lazy deletion

Two balanced heaps give the median at the top, and lazy deletion removes the element that leaves the window in O(log k). A sorted array insertion costs O(k) per shift.

More Coding Interview Problems questions

Exams that ask this topic