Find Median From Data Stream

Problem

Design a data structure that supports adding numbers from a stream one at a time and, at any point, can efficiently return the median of all numbers seen so far.

Examples

Example 1
Input:addNum(1); addNum(2); findMedian()
Output:1.5
Example 2
Input:addNum(3); findMedian()
Output:2

Constraints

  • -10^5 <= num <= 10^5
  • Up to 5 * 10^4 calls total.

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Heap / Priority Queue pattern

A heap keeps the minimum (or maximum) element accessible in O(1), with O(log n) insert and remove. It's the tool whenever you repeatedly need "the smallest/largest remaining item" without needing everything fully sorted.

Look for this pattern when

  • You need the top-k largest/smallest elements, not a full sort.
  • You're merging multiple sorted sequences (always take the smallest available head).
  • You need a running min/max/median as data streams in.

Read the full Heap / Priority Queue guide →

Video walkthroughs

Original problem on LeetCode ↗

More Heap / Priority Queue problems