Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half).

Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half).
import heapq
def medians(stream):
    lo, hi, out = [], [], []
    for x in stream:
        heapq.heappush(lo, -x)
        heapq.heappush(hi, -heapq.heappop(lo))
        if len(hi) > len(lo): heapq.heappush(lo, -heapq.heappop(hi))
        m = -lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2
        out.append(f"{m:g}")
    return " ".join(out)
print(medians([5, 15, 1, 3, 2, 8]))
What is printed?
  1. A. 5 10 5 4 2 4
  2. B. 5 10 5 4 3 4
  3. C. 5 10 1 3 2 2
  4. D. 5 10 5 3 3 4

Correct answer: B. 5 10 5 4 3 4

Sorted prefixes: [5] → 5; [5, 15] → 10; [1, 5, 15] → 5; [1, 3, 5, 15] → 4; [1, 2, 3, 5, 15] → 3; [1, 2, 3, 5, 8, 15] → (3 + 5)/2 = 4. Every push goes through both heaps so the max of the lower half never exceeds the min of the upper half.

More Coding Interview Problems questions

Exams that ask this topic