InterviewPrepKit

Home / Coding / Heap & Priority Queue

Find Median from Data Stream

hard Original β†—
Solving tips
  • Key insight: the median only needs the boundary between the lower and upper halves, so keep a max-heap (lower half) and a min-heap (upper half) balanced within 1 in size.
  • On add, route through one heap then move its extreme to the other to preserve cross-heap ordering, then rebalance sizes β€” never push directly onto whichever 'looks right'.
  • In Python negate values for the max-heap; use / 2 (float) for the even-count median, not integer division.
  • Target O(log n) per add and O(1) per findMedian; pick one size convention (e.g. lower may be one larger) and make rebalance and query agree.

Problem

Design a data structure that receives integers one at a time and can report the median of everything seen so far at any moment.

The median is the middle value of the sorted data: for an odd count it is the single middle element; for an even count it is the average of the two middle elements (so it may be fractional).

Implement the class MedianFinder:

  • MedianFinder() β€” initializes the structure.
  • addNum(num: int) β€” adds num from the stream.
  • findMedian() -> float β€” returns the median of all numbers added so far.

Examples

  • addNum(1), addNum(2), findMedian() β†’ 1.5 Sorted data is [1, 2]; even count, so the median is (1 + 2) / 2.
  • addNum(3) (continuing), findMedian() β†’ 2.0 Sorted data is [1, 2, 3]; odd count, the middle element is 2.
  • addNum(5), addNum(-1), addNum(5) (continuing), findMedian() β†’ 2.5 Sorted data is [-1, 1, 2, 3, 5, 5]; six elements, so the median averages the 3rd and 4th: (2 + 3) / 2.

Constraints

  • -10^5 <= num <= 10^5
  • findMedian is only called after at least one addNum
  • Up to 5 * 10^4 calls total to addNum and findMedian β€” per-call cost must be far below linear-with-sort

Think about it first

Hint 1 Keeping the data fully sorted is more than you need. To produce a median you only ever need fast access to the one or two elements at the *center*.
Hint 2 Split the numbers into a "lower half" and an "upper half" of equal (Β±1) size. The median is determined entirely by the largest of the lower half and the smallest of the upper half.
Hint 3 Store the lower half in a max-heap and the upper half in a min-heap. On every insert, push onto one heap, then move its root to the other; rebalance if the sizes drift more than 1 apart. Both roots are then the two center elements.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.