Find Median from Data Stream (LeetCode 295): Solution and Explanation
Build a MedianFinder class that accepts integers one at a time through addNum and can report the median of everything seen so far through findMedian. With an odd count the median is the middle value, and with an even count it is the average of the two middle values.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest design keeps every number in a list and sorts it whenever the median is requested, which is O(n log n) per query. Keeping the list sorted with insertion is better, since binary search finds the position in O(log n), but shifting elements to make room still costs O(n) per add. With many interleaved calls, both approaches get slow.
Notice that the median only depends on the boundary between the smaller half and the larger half of the data. You do not need the halves sorted internally; you just need fast access to the largest value of the lower half and the smallest value of the upper half. That is exactly what a max-heap and a min-heap provide.
So keep the lower half in a max-heap called small and the upper half in a min-heap called large. Two invariants make this work: every value in small is at most every value in large, and the two sizes differ by at most one. Each insert might break one of these, but fixing it takes at most a couple of heap moves. Then the median is the top of the bigger heap, or the average of both tops when the sizes are equal. Python only has a min-heap, so small stores negated values.
Approach: Two heaps split at the median
- Keep
smallas a max-heap (stored as negatives) for the lower half andlargeas a min-heap for the upper half. - In
addNum, push the new number ontosmallfirst. - If the largest value in
smallis greater than the smallest value inlarge, pop it fromsmalland push it ontolargeso the ordering invariant holds. - If
smallhas more than one extra element, move its top tolarge. Iflargehas more than one extra element, move its top tosmall. - In
findMedian, return the top of whichever heap is larger. If the sizes are equal, return the average of both tops.
Step-by-step example
addNum(1), addNum(2), findMedian(), addNum(3), findMedian()
- Add 1: it goes into
small.largeis empty, so nothing moves. Nowsmallholds {1}. - Add 2: it goes into
small, whose top is now 2.largeis empty so the ordering check is skipped, butsmallhas 2 elements against 0, so 2 moves tolarge. - findMedian: the sizes are equal, so return (1 + 2) / 2 = 1.5.
- Add 3: it goes into
small, making its top 3. Since 3 is greater than the top oflarge(2), move 3 tolarge, which now holds {2, 3}. - The sizes are 1 and 2, a difference of one, so no rebalance is needed. findMedian returns the top of
large, which is 2.
Code: Python, Java, C++
1class MedianFinder:
2 def __init__(self):
3 self.small, self.large = [], []
4
5 def addNum(self, num: int) -> None:
6 heapq.heappush(self.small, -1 * num)
7
8 # Make sure every num small is <= every num in large
9 if self.small and self.large and (-1 * self.small[0]) > self.large[0]:
10 val = -1 * heapq.heappop(self.small)
11 heapq.heappush(self.large, val)
12
13 # Uneven size?
14 if len(self.small) > len(self.large) + 1:
15 val = -1 * heapq.heappop(self.small)
16 heapq.heappush(self.large, val)
17 if len(self.large) > len(self.small) + 1:
18 val = heapq.heappop(self.large)
19 heapq.heappush(self.small, -1 * val)
20
21 def findMedian(self) -> float:
22 if len(self.small) > len(self.large):
23 return -1 * self.small[0]
24 if len(self.large) > len(self.small):
25 return self.large[0]
26 return (-1 * self.small[0] + self.large[0]) / 21class MedianFinder {
2 PriorityQueue<Integer> small = new PriorityQueue<>(Collections.reverseOrder());
3 PriorityQueue<Integer> large = new PriorityQueue<>();
4
5 public void addNum(int num) {
6 small.add(num);
7 if (small.size() > 0 && large.size() > 0 && small.peek() > large.peek()) {
8 large.add(small.poll());
9 }
10 if (small.size() > large.size() + 1) {
11 large.add(small.poll());
12 }
13 if (large.size() > small.size() + 1) {
14 small.add(large.poll());
15 }
16 }
17
18 public double findMedian() {
19 if (small.size() > large.size()) return small.peek();
20 if (large.size() > small.size()) return large.peek();
21 return (small.peek() + large.peek()) / 2.0;
22 }
23}1class MedianFinder {
2 priority_queue<int> small;
3 priority_queue<int, vector<int>, greater<int>> large;
4public:
5 void addNum(int num) {
6 small.push(num);
7 if (!small.empty() && !large.empty() && small.top() > large.top()) {
8 large.push(small.top());
9 small.pop();
10 }
11 if (small.size() > large.size() + 1) {
12 large.push(small.top());
13 small.pop();
14 }
15 if (large.size() > small.size() + 1) {
16 small.push(large.top());
17 large.pop();
18 }
19 }
20
21 double findMedian() {
22 if (small.size() > large.size()) return small.top();
23 if (large.size() > small.size()) return large.top();
24 return (small.top() + large.top()) / 2.0;
25 }
26};Time and space complexity
O(log n) per addNum, O(1) per findMedian
Each insert does a constant number of heap pushes and pops, each costing O(log n). Reading the median only looks at heap tops.
O(n)
Every number added is stored in exactly one of the two heaps.
Other approaches
Sorted list with binary insertion (time O(n) per add, O(1) per median, space O(n))
Keep a sorted array, use binary search to find each insert position, and read the middle element directly. Queries are O(1), but inserting shifts elements, so each add is O(n).
Counting buckets for a small value range (time O(1) per add, O(R) per median, space O(R))
If all numbers fall in a small fixed range such as 0 to 100, keep a count per value and scan the counts to locate the middle positions. Adds are O(1) and queries cost the size of the range.
Common mistakes
- Forgetting to negate values when using Python's min-heap as a max-heap, both when pushing and when reading the top.
- Rebalancing sizes without first fixing the ordering. A large number pushed into
smallmust move tolargeeven if the sizes look fine. - Using integer division for the even case. The median of 1 and 2 is 1.5, so divide as a float.
- Letting the heaps drift more than one element apart, which makes the tops stop representing the middle.
Frequently asked questions
Why use two heaps to find a running median?
The median sits at the boundary between the lower and upper halves. A max-heap gives instant access to the top of the lower half and a min-heap to the bottom of the upper half, and both support O(log n) inserts.
What is the time complexity of the two-heap median finder?
Each addNum is O(log n) because of a constant number of heap operations, and each findMedian is O(1). Space is O(n) for storing all numbers.
How do you implement a max-heap in Python?
The heapq module only provides a min-heap, so push the negated value and negate again when you read or pop. The smallest negated value is the largest original value.
How would you handle a sliding window median instead?
You still use two halves, but you also need to remove values that leave the window. Lazy deletion with a hash map of pending removals, or a balanced sorted structure, handles that efficiently.