The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
- For example, for
arr = [2,3,4], the median is3. - For example, for
arr = [2,3], the median is(2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder()initializes theMedianFinderobject.void addNum(int num)adds the integernumfrom the data stream to the data structure.double findMedian()returns the median of all elements so far. Answers within10-5of the actual answer will be accepted.
Example 1:
Input [“MedianFinder”, “addNum”, “addNum”, “findMedian”, “addNum”, “findMedian”] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0]
Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0
Constraints:
-105 <= num <= 105- There will be at least one element in the data structure before calling
findMedian. - At most
5 * 104calls will be made toaddNumandfindMedian.
Follow up:
- If all integer numbers from the stream are in the range
[0, 100], how would you optimize your solution? - If
99%of all integer numbers from the stream are in the range[0, 100], how would you optimize your solution?
Approach: Two Heaps (Max-Heap + Min-Heap)
Algorithm
- Keep two heaps: a max-heap for the smaller half of the numbers and a min-heap for the larger half
addNum: push into the max-heap, then move the largest element to the min-heap; rebalance so the two heaps differ in size by at most onefindMedian: if the sizes are equal, average the two roots; otherwise return the root of the larger heap
Time & Space Complexity
- Time Complexity: O(log n) per
addNum; O(1) perfindMedian - Space Complexity: O(n) - all stream elements are stored
Java Implementation
import java.util.Collections;
import java.util.PriorityQueue;
public class MedianFinder {
private final PriorityQueue<Integer> maxHeap;
private final PriorityQueue<Integer> minHeap;
public MedianFinder() {
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap = new PriorityQueue<>();
}
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
if (maxHeap.size() < minHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
}
return (maxHeap.peek() + minHeap.peek()) / 2.0;
}
// Test method
public static void main(String[] args) {
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);
medianFinder.addNum(2);
System.out.println(medianFinder.findMedian()); // return 1.5
medianFinder.addNum(3);
System.out.println(medianFinder.findMedian()); // return 2.0
}
}
Example Walkthrough
Inserting 1, 2, 3:
- addNum(1): maxHeap={1}, sizes equal
- addNum(2): push 2 to maxHeap -> maxHeap={2,1}; move max to minHeap -> maxHeap={1}, minHeap={2}. Even sizes, median=(1+2)/2=1.5
- addNum(3): push to maxHeap -> maxHeap={3,1}; move max to minHeap -> maxHeap={1}, minHeap={2,3}; rebalance since maxHeap < minHeap -> maxHeap={2,1}, minHeap={3}. maxHeap larger, median=2.0
Key Points
- Invariant:
maxHeapholds the smaller half,minHeapholds the larger half, and sizes differ by at most one - Top of Heaps: The median candidates are always the roots of the two heaps
- Balancing Step: The
maxHeapis never smaller thanminHeap, keeping the median inmaxHeapfor odd sizes - Follow-Up: For bounded ranges [0,100], a frequency array with prefix sums gives O(100) operations
- Precision: Averaging in double arithmetic keeps results within the
10-5tolerance