Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half).

Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half).
import heapq
lo, hi, out = [], [], []
for x in [5, 15, 1, 3, 8]:
    heapq.heappush(lo, -x)
    heapq.heappush(hi, -heapq.heappop(lo))
    if len(hi) > len(lo):
        heapq.heappush(lo, -heapq.heappop(hi))
    out.append(-lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2)
print(out)
What is printed?
  1. A. [5, 10.0, 5, 3, 5]
  2. B. [5, 10.0, 1, 4.0, 5]
  3. C. [5, 15, 5, 4.0, 8]
  4. D. [5, 10.0, 5, 4.0, 5]

Correct answer: D. [5, 10.0, 5, 4.0, 5]

Every number passes through lo into hi, and hi gives one back if it becomes larger, so lo always holds the smaller half (size equal or one more). Medians: 5; (5+15)/2 = 10.0; 5 of {1,5,15}; (3+5)/2 = 4.0 of {1,3,5,15}; 5 of {1,3,5,8,15}. O(log n) per insert, O(1) per median query.

More Coding Interview Problems questions

Exams that ask this topic