Patterns

TH · Pattern 09

Two Heaps

Maintain a max-heap for the lower half and a min-heap for the upper half of a stream. The median is always at their tops.

Two Heaps
Time
O(log n) per insertion
Space
O(n)

Spot it when

  • Find median from data stream
  • Problems requiring dynamic "middle" element
  • Scheduling with two priority groups