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:

Example 1
Input: addNum(1), addNum(2), findMedian(), addNum(3), findMedian()
Output: 1.5, 2.0
Solution

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.

The numbers 5, 15, 1, 3, 8, 7 sorted are 1, 3, 5, 7, 8, 15. The lower half 1, 3, 5 is kept in a max-heap with 5 on top; the upper half 7, 8, 15 is kept in a min-heap with 7 on top. The median is (5 + 7) / 2 = 6.

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? PriorityQueue from java.util is one. By default it is a min-heap: peek() returns its smallest value, and poll() removes and returns it. A plain PriorityQueue, named high, holds the upper half.

For the lower half, named low, the constructor gets a comparator, an object that decides which of two values comes first: new PriorityQueue<>(Collections.reverseOrder()). Collections.reverseOrder() flips the natural order, so larger numbers come first and low becomes a max-heap.

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 low, then take the largest value out of low and move it into high.

If the new number is large, it is the largest value in low, so it moves straight on to high. If it is small, it stays in low, and the old top of low moves up instead. Either way, every value left in low is at most every value in high.

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 low: low holds as many numbers as high, or one more.

Every new number ends up making high one larger. If high now holds more than low, its smallest value moves back down. In Example 1, low holds 1 and high holds 2 when 3 arrives. 3 goes into low and straight on to high, which now holds 2 and 3. That is one too many, so 2 moves back, and low holds 1 and 2.

Working out the median

How do the tops give the median? With an odd count, low holds the extra number, and its top is the middle value: 2 in Example 1. With an even count, the median is the average of both tops. That average needs care, because int division drops the .5, and two large int values can add up to more than an int holds. Turning one top into a double before adding avoids both.

Java Solution

The class has four parts, one for each piece of the approach:

  • low: the lower half, a max-heap built with Collections.reverseOrder() as its comparator, so peek() gives its largest value.
  • high: the upper half, a plain PriorityQueue, which is a min-heap, so peek() gives its smallest value.
  • addNum: passes the number through low into high, then moves the smallest value of high back if high has grown larger than low.
  • findMedian: returns the top of low for an odd count, or the average of both tops, worked out in double, for an even count.

The main method runs Example 1, then adds 5, 15, 1, 3, 8 and 7 from the picture, printing the median after each and then the two heaps. It ends with two negative numbers and with two copies of Integer.MAX_VALUE, the largest int.

Java
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:

Output
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] and high [7, 15, 8]. Printing a PriorityQueue shows the values in the order it stores them, and only the first is sure to be the top. In low, 1 comes before 3, so the rest really are in no set order.

The last two lines are the average at work. -1 and -2 give -1.5, with the .5 kept. Two copies of Integer.MAX_VALUE give 2.147483647E9, which is 2,147,483,647 written as a double (E9 means times 109).

Averaging the tops as int values, (low.peek() + high.peek()) / 2, gets both of those wrong. A small check program prints 1 for the tops 1 and 2, because int division drops the .5. For two Integer.MAX_VALUE tops it prints -1: their int sum is too big to fit, comes out as -2, and is then halved.

Complexity

addNum does a fixed number of heap operations, and findMedian only looks at the two tops.

  • Time: O(log n) per addNum, because it makes at most five add or poll 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.
  • Time: O(1) per findMedian, because peek() reads the top of a heap without changing it.
  • 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 Sliding Window Median.