Find Median from Data Stream
Keep the median of a growing collection of numbers ready at any moment, using two heaps.
Write a class that receives integers one at a time and can report, at any moment, the median of all the numbers received so far. The median is the middle value once the numbers are sorted. When the count is even, it is the average of the two middle values. The class has two methods:
adds a number;addNum(int num) returns the median of the numbers added so far, as afindMedian() .double
Example 1
Output: 1.5, 2.0
The Idea
Think of a teacher entering test scores one by one, who wants to see the middle score after every entry. Unlike the average, the median barely moves when one score is unusually high or low. The scores keep coming, so the answer has to be ready at any point, not only at the end.
Follow Example 1. After 1 and 2, the sorted numbers are 1, 2. The count is even, so the median is the average of the two middle values, (1 + 2) / 2 = 1.5. Then 3 arrives. The sorted numbers are 1, 2, 3, and the median is the middle one, 2.0.
The plain way is to keep every number in a sorted list. Reading the median is then quick, since it sits in the middle. But each new number has to be slotted into its place, and in a list of n numbers that can mean shifting n numbers along. Do we really need the whole list in order?
Take a longer stream: 5, 15, 1, 3, 8, 7. Sorted, it reads 1, 3, 5, 7, 8, 15, and the median is (5 + 7) / 2 = 6. Only 5 and 7 took part. 5 is the largest number of the lower half, and 7 is the smallest number of the upper half. How the other numbers inside each half are ordered never mattered.
So we need two groups, each with one value always ready: the largest of the lower half, and the smallest of the upper half. A structure that keeps its largest value ready on top, and takes in a value or gives up its top in a few steps, is called a max-heap. A min-heap is the same with its smallest value on top. Look at the picture below.
In the top row, the dashed line splits the sorted numbers into the lower half, 1, 3 and 5, and the upper half, 7, 8 and 15. The lower half is kept in a max-heap, so 5 is on top. The upper half is kept in a min-heap, so 7 is on top. Below each top, the rest sit in no set order. The median box at the bottom uses only the two tops.
That splits the work in two. Each new number has to land in the right half, with the halves kept the same size. Reading the median then only means looking at two tops.
Solution Approach
Turning that idea into code means settling four things: which Java class holds each half, where a new number goes, how to keep the halves the same size, and how to work out the median from the two tops.
Two PriorityQueues
Which Java class gives us a heap? PriorityQueuejava.utilpeek()poll()PriorityQueuehigh
For the lower half, named lownew PriorityQueue<>(Collections.reverseOrder())Collections.reverseOrder()low
Where a new number goes
Which half does a new number belong to? We could compare it with both tops, but a shorter route needs no comparison. Put the number into lowlowhigh
If the new number is large, it is the largest value in lowhighlowlowlowhigh
Keeping the halves the same size
Why does the size matter? The two tops are the middle values only if the halves hold the same count, or one holds one extra. Here the extra one goes to lowlowhigh
Every new number ends up making highhighlowlowhighlowhighlow
Working out the median
How do the tops give the median? With an odd count, lowintintintdouble
Java Solution
The class has four parts, one for each piece of the approach:
: the lower half, a max-heap built withlow as its comparator, soCollections.reverseOrder() gives its largest value.peek() : the upper half, a plainhigh , which is a min-heap, soPriorityQueue gives its smallest value.peek() : passes the number throughaddNum intolow , then moves the smallest value ofhigh back ifhigh has grown larger thanhigh .low : returns the top offindMedian for an odd count, or the average of both tops, worked out inlow , for an even count.double
The mainInteger.MAX_VALUEint
import java.util.Collections;
import java.util.PriorityQueue;
public class FindMedianFromDataStream {
// lower half, largest on top (max-heap)
private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());
// upper half, smallest on top (min-heap)
private final PriorityQueue<Integer> high = new PriorityQueue<>();
public void addNum(int num) {
low.add(num);
high.add(low.poll()); // low's largest moves up, so low stays below high
if (high.size() > low.size()) {
low.add(high.poll()); // keep low the same size as high, or one bigger
}
}
public double findMedian() {
if (low.size() > high.size()) {
return low.peek(); // odd count: the middle value
}
return ((double) low.peek() + high.peek()) / 2.0; // even count: average of two
}
public static void main(String[] args) {
FindMedianFromDataStream example = new FindMedianFromDataStream();
example.addNum(1);
example.addNum(2);
System.out.print(example.findMedian() + " ");
example.addNum(3);
System.out.println(example.findMedian());
FindMedianFromDataStream stream = new FindMedianFromDataStream();
StringBuilder medians = new StringBuilder();
for (int num : new int[] {5, 15, 1, 3, 8, 7}) {
stream.addNum(num);
medians.append(stream.findMedian()).append(' ');
}
System.out.println(medians.toString().trim());
System.out.println("low " + stream.low + ", high " + stream.high);
FindMedianFromDataStream negatives = new FindMedianFromDataStream();
negatives.addNum(-1);
negatives.addNum(-2);
System.out.println(negatives.findMedian());
FindMedianFromDataStream big = new FindMedianFromDataStream();
big.addNum(Integer.MAX_VALUE);
big.addNum(Integer.MAX_VALUE);
System.out.println(big.findMedian());
}
}
Running it prints:
1.5 2.0
5.0 10.0 5.0 4.0 5.0 6.0
low [5, 1, 3], high [7, 15, 8]
-1.5
2.147483647E9
The first line, 1.5 and 2.0, is the answer to Example 1. The second line follows the stream from the picture: 5.0 while 5 is alone, 10.0 once 15 joins, and finally 6.0, the (5 + 7) / 2 from the picture.
The third line prints the heaps themselves, low [5, 1, 3]high [7, 15, 8]PriorityQueuelow
The last two lines are the average at work. -1 and -2 give -1.5, with the .5 kept. Two copies of Integer.MAX_VALUEdouble
Averaging the tops as int(low.peek() + high.peek()) / 2intInteger.MAX_VALUEint
Complexity
addNumfindMedian
- Time: O(log n) per
, because it makes at most fiveaddNum oradd calls, and each of them takes O(log n) steps on a heap of at most n numbers, where n is how many numbers have been added so far.poll - Time: O(1) per
, becausefindMedian reads the top of a heap without changing it.peek() - Space: O(n), because every number added stays in exactly one of the two heaps.
When old numbers must also leave, as in a window that slides along an array, see