Skip to content
Preptima
mediumCodingDesignMidSeniorStaff

Numbers arrive one at a time and after each one I want the running median. How would you keep it?

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Split the values across a max-heap of the lower half and a min-heap of the upper half, so the median is read off one or both tops. Balancing by size alone is what breaks it: a new value has to enter through the heap it belongs to by value and be transferred across, never pushed into whichever heap is currently smaller.

Was this answer helpful?

Likely follow-ups

  • Now give me the median of the last k values only. What breaks, and what do you replace the heaps with?
  • I want the 95th percentile rather than the median. Do two heaps still work?
  • Values can be removed as well as added, by value not by position. What now?
  • Memory is bounded and the stream is unbounded. What accuracy would you trade away, and for what?

Related questions