Problem
Design a structure that accepts integers one at a time and can return the median of all values seen so far. If the count is even, return the average of the two central values as a double.
Original: LeetCode 295: Find Median from Data Stream.
Examples
Example 1
`MedianFinder: addNum(1), addNum(2), findMedian(), addNum(3), findMedian()``[null, null, 1.5, null, 2.0]`Constraints
-10^5 <= num <= 10^5- There will be at least one element in the data structure before calling
findMedian. - At most
5 * 10^4calls will be made toaddNumandfindMedian.
Hints
Hint 1
The median is defined on the sorted stream. You must support many add and find operations, so you cannot sort from scratch each time.
Hint 2
A running median is the two-heaps pattern: the largest of the small half and the smallest of the large half meet in the middle.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Keep an array, sort it on each query, and read the middle.
Optimal. A max-heap low and a min-heap high. Insert into low by default, then move values so every item in low is <= every item in high, and the sizes differ by at most one.
Alternative. An insertion-ordered list or a balanced tree with an index also works, with logarithmic inserts and a direct middle lookup.
Complexity
- Time
- O(log n)
Each add is O(log n). findMedian is O(1). Space is O(n).
- Space
- O(n)
Code
import heapq
class MedianFinder:
def __init__(self) -> None:
self.low: list[int] = [] # max-heap via negation
self.high: list[int] = [] # min-heap
def add_num(self, num: int) -> None:
heapq.heappush(self.high, -heapq.heappushpop(self.low, -num))
if len(self.low) < len(self.high):
heapq.heappush(self.low, -heapq.heappop(self.high))
def find_median(self) -> float:
if len(self.low) > len(self.high):
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2.0
if __name__ == "__main__":
m = MedianFinder()
m.add_num(1)
m.add_num(2)
assert m.find_median() == 1.5
m.add_num(3)
assert m.find_median() == 2.0
print("ok")import java.util.PriorityQueue;
public class FindMedianFromDataStream {
private final PriorityQueue<Integer> low = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
private final PriorityQueue<Integer> high = new PriorityQueue<>();
void addNum(int num) {
low.offer(num);
high.offer(low.poll());
if (low.size() < high.size()) low.offer(high.poll());
}
double findMedian() {
if (low.size() > high.size()) return low.peek();
return (low.peek() + high.peek()) / 2.0;
}
public static void main(String[] args) {
var m = new FindMedianFromDataStream();
m.addNum(1);
m.addNum(2);
if (m.findMedian() != 1.5) throw new AssertionError(m.findMedian());
m.addNum(3);
if (m.findMedian() != 2.0) throw new AssertionError(m.findMedian());
System.out.println("ok");
}
}Edge cases
- Official sample: add 1, add 2, median 1.5; add 3, median 2.0.
- Negative numbers work as long as the max-heap comparison is correct. In Python the lower half is stored negated.
Follow-ups
- Sliding window median evicts old values; you need lazy deletion or a tree map in addition to the two heaps.
Interview script
"I split the stream into a max-heap of the lower half and a min-heap of the upper half, and I rebalance after every insert so their sizes differ by at most one. The median is then one root, or the average of both roots."
Source: LeetCode 295: Find Median from Data Stream Source: Java SE 17 API: PriorityQueue
Sources (2)
- LeetCode 295: Find Median from Data Streamleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com