All coding questions

Find Median from Data Stream

hard
NeetCode 150heapdesign

Problem

Design a structure that accepts a stream of integers and can report the running median at any time. Support adding a number and querying the current median efficiently.

Examples

Input: add 1, add 2, median, add 3, median
Output: 1.5 then 2
Median tracks the middle of all seen values.

Constraints

  • At most 5 * 10^4 operations
  • -10^5 <= each value <= 10^5
Hints(tap to reveal)
  • 1. Split the data into a lower half and an upper half.
  • 2. Two heaps kept balanced expose the median at their tops.
Optimal approach(spoiler)
  1. Keep a max-heap for the lower half and a min-heap for the upper half.
  2. On insert, push to the appropriate heap then rebalance sizes by at most one.
  3. If sizes are equal the median averages the two heap tops.
  4. Otherwise it is the top of the larger heap.
  5. Insert is O(log n); median query is O(1).

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor