295. Find Median from Data Stream
Asked at Google, Meta, Amazon, Microsoft and 6 more
Difficulty
Hard
Time
O(log n) for addNum, O(1) for fi
Space
O(n)
Pattern
Heap
Companies
10
Problem
Design a class called MedianFinder that keeps track of numbers arriving one at a time from a stream, and can report the median of everything seen so far at any moment.
The median is the middle value when all numbers are sorted. If the count is odd, it is the single middle element. If the count is even, there is no single middle, so take the average of the two middle values. For example, the median of [2,3,4] is 3, and the median of [2,3] is 2.5.
Implement two methods: addNum(num) stores a new integer, and findMedian() returns the median of all stored numbers as a double. findMedian() is only called when at least one number has been added. Answers within 10^-5 of the true value are accepted.
The median splits the data in half
Constraints
- ●
-10^5 <= num <= 10^5 - ●
findMedian is called only when the structure holds at least one element - ●
At most 5 * 10^4 total calls to addNum and findMedian
Examples
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []][null, null, null, 1.5, null, 2.0]Asked At
10 companies| Company | Difficulty | |
|---|---|---|
| Hard | View all Google questions → | |
| Meta | Hard | View all Meta questions → |
| Amazon | Hard | View all Amazon questions → |
| Microsoft | Hard | View all Microsoft questions → |
| Apple | Hard | View all Apple questions → |
| Netflix | Hard | View all Netflix questions → |
| Uber | Hard | View all Uber questions → |
| Atlassian | Hard | View all Atlassian questions → |
| TikTok | Hard | View all TikTok questions → |
| DE Shaw | Hard | View all DE Shaw questions → |
How to Think About It
Use two heaps: a max-heap for the lower half and a min-heap for the upper half.
Balance invariant: the max-heap can have at most one more element than the min-heap. This ensures the median is always at the top of one or both heaps.
On addNum: push to one heap, then rebalance. If the max of lower half > min of upper half, swap them.
Median: if sizes differ, return the max-heap top (extra element). Otherwise, average both tops.
Edge cases: single element (that element), even/odd count, negative numbers.
Optimal Approach
class MedianFinder:
lo = [] (max-heap, store negatives)
hi = [] (min-heap)
addNum(num):
push -num to lo
push -heappop(lo) to hi (move max of lo to hi)
if len(hi) > len(lo): push -heappop(hi) to lo (rebalance)
findMedian():
if len(lo) > len(hi): return -lo[0]
return (-lo[0] + hi[0]) / 2
Time: O(log n) add, O(1) find. Space: O(n).
Two heaps, one for each half
What Trips People Up in Real Interviews
Using a sorted list. Insert is O(n), not O(log n). Use two heaps for O(log n) insert.
Confusing "median" with "mean." The median is the middle value (odd count) or average of two middle values (even count).
Not maintaining the balance invariant. The max-heap can have at most one more element than the min-heap.
Forgetting to handle the case where heaps are equal size. The average of both tops is the median.
Pushing to the wrong heap first. Always push to lo (max-heap), then move the max of lo to hi (min-heap), then rebalance. Pushing to hi first can break the balance invariant.
Solution Code
O(log n) for addNum, O(1) for fi timeimport heapq
class MedianFinder:
def __init__(self):
self.lo = [] # max-heap (inverted)
self.hi = [] # min-heap
def addNum(self, num):
heapq.heappush(self.lo, -num)
heapq.heappush(self.hi, -heapq.heappop(self.lo))
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
def findMedian(self):
if len(self.lo) > len(self.hi):
return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2Frequently Asked Questions
What is the Find Median from Data Stream problem?
Design a data structure that supports addNum(int num) and findMedian() in `O(log n)` and `O(1)` time respectively. This is a classic system design and algorithm hybrid question.
How do you solve Find Median from Data Stream?
The optimal approach runs in O(log n) for addNum, O(1) for fi time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.
What companies ask Find Median from Data Stream?
Find Median from Data Stream is asked at Google, Meta, Amazon, Microsoft, Apple, Netflix, Uber, Atlassian, TikTok, DE Shaw. It is a hard difficulty problem.
What are common mistakes on Find Median from Data Stream?
- Using a sorted list. Insert is `O(n)`, not `O(log n)`. Use two heaps for `O(log n)` insert.
- Confusing "median" with "mean." The median is the middle value (odd count) or average of two middle values (even count).
- Not maintaining the balance invariant. The `max-heap` can have at most one more element than the `min-heap`.
- Forgetting to handle the case where heaps are equal size. The average of both tops is the median.
- Pushing to the wrong heap first. Always push to lo (`max-heap`), then move the max of lo to hi (`min-heap`), then rebalance. Pushing to hi first can break the balance invariant.