Skip to content

Practice Find Median from Data Stream

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#295
LeetCode Problem

Find Median from Data Stream

Problem Statement

Implement MedianFinder(), addNum(num), and findMedian(). Insertions add integers to the collection. With an odd count, the median is the middle sorted value; with an even count, it is the average of the two middle values. findMedian is called only after at least one insertion. Practice approach: Keep a max-heap for the lower half and a min-heap for the upper half. Rebalance after each insertion so their sizes differ by at most one and every lower-half value is no larger than any upper-half value. Read one heap top or average both tops. Insertion is O(log n), median lookup O(1), and storage O(n).

Source: Find Median from Data Stream on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
MedianFinder(); addNum(8); findMedian(); addNum(2); findMedian(); addNum(4); findMedian()
Output
[null,null,8,null,5,null,4]
Explanation

The medians of [8], [2,8], and [2,4,8] are 8, 5, and 4.

Constraints

-100000 <= num <= 100000
At most 50000 addNum and findMedian calls.
At least one number exists before findMedian.

How to solve Find Median from Data Stream

Original notes for interview preparation, written for this problem. Reviewed .

Key insight

The median depends only on the boundary between the lower and upper halves, not the full sorted order, so two heaps exposing exactly that boundary let each insertion repair the split in logarithmic time.

Why brute force is not enough

Keeping a sorted list and inserting with binary search still costs O(n) per insertion for the shift, about 1.25 * 10^9 element moves over 50000 calls; sorting on every findMedian is worse at O(n log n) per query.

Approach

  1. Keep a max-heap for the lower half and a min-heap for the upper half under two invariants: every lower value is at most every upper value, and the lower heap is the same size as the upper or exactly one larger.
  2. On insertion, push the number into the lower heap, then move that heap's maximum into the upper heap; the value that crosses is at least as large as everything left behind, so ordering holds.
  3. If the upper heap is now larger, move its minimum back down; this restores the size invariant without breaking the ordering.
  4. To report, return the lower heap's top for an odd count, or the average of both tops for an even count, using floating-point division.

Walkthrough of Example 1

MedianFinder(); addNum(8); findMedian(); addNum(2); findMedian(); addNum(4); findMedian() → [null,null,8,null,5,null,4]

  1. addNum(8): push 8 into lower, move it to upper, then since upper is larger move it back; lower is {8}, upper is empty. findMedian returns the lower top, 8.
  2. addNum(2): push 2 into lower giving {2, 8}, then move the maximum 8 to upper; lower is {2}, upper is {8}, sizes equal.
  3. findMedian: even count, so average the tops: (2 + 8) / 2 = 5.
  4. addNum(4): push 4 into lower giving {2, 4}, move the maximum 4 to upper giving {4, 8}; upper is now larger, so move 4 back, leaving lower {2, 4} and upper {8}.
  5. findMedian: odd count, so the lower top 4 is the median. The outputs 8, 5, 4 match [null,null,8,null,5,null,4].

Time and space

Time O(log n) per addNum, O(1) per findMedian · Space O(n). n is the number of values inserted so far; each insertion performs a constant number of O(log n) heap operations, and the two heaps together store every value.

Interview pitfalls

  • Choosing a heap by comparing with one top; that breaks when the heap is empty or the value falls between the tops, which push-then-transfer avoids.
  • Integer division when averaging, which turns 2 and 5 into 3 instead of 3.5.
  • Letting the sizes drift apart by two or more, so the median reads the wrong element.
  • Simulating the max-heap by negating values in a min-heap library and forgetting to negate on read, especially confusing with the negative inputs allowed here.

Follow-up questions interviewers ask

  • How would you support removals, as in a sliding window median, and which structure handles deletions?
  • Since values are bounded between -100000 and 100000, can counting give O(1) insertion?

Further reading on the technique: Heap (data structure)

Related LeetCode Problems

Practice more problems similar to Find Median from Data Stream.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.