← Whiteboard questions

Find Median From Data Stream

Report the middle value as numbers keep arriving

DSA, Hard, Heap / Priority Queue

Which structure or algorithm, and what does it cost.

Build a class MedianTracker that starts empty. The method add(num) records one whole number. The method median() returns the middle value of all numbers recorded so far, as a decimal. With an even count, it returns the average of the two middle values. The example input is a list ops of calls in order, each ["add", n] or ["median"]. Return the list of what the median calls returned, in order.

Examples

Input ops = [["add", 6], ["add", 2], ["median"], ["add", 10], ["median"], ["add", 3], ["median"]]
Output [4.0, 6.0, 4.5]
Why with 2 and 6 the middle pair averages to 4.0. With 2, 6, 10 the middle is 6. With 2, 3, 6, 10 the middle pair is 3 and 6.
Input ops = [["add", -7], ["median"]]
Output [-7.0]
Why a single number is its own median.
Input ops = [["add", 4], ["median"], ["add", 4], ["add", 4], ["add", 1], ["median"]]
Output [4.0, 4.0]
Why repeated values count separately. With 1, 4, 4, 4 the middle pair is 4 and 4.

Constraints

Your answer must contain

Target Aim for O(log n) time per add, O(1) per median, and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

The median sits in the middle of the sorted numbers. Ask which numbers you must look at to find it, and which you can ignore.

Hint 2 the approach

Split the numbers into a lower half and an upper half. The median comes from the edges where the two halves meet.

Hint 3 the key step

Keep the lower half where its largest is at hand and the upper half where its smallest is at hand. What must stay true about their sizes?

Walkthrough

Full walkthrough brute force to best

Brute force

Store every number in a list. For each median call, sort the list and read the middle. A sort per call costs O(n log n), so 100,000 calls is far too slow. Memory is O(n).

Better method

Keep the list sorted all the time. To add a number, find its place with binary search and insert it there. A median call then reads the middle in O(1). The search is O(log n), but the insert shifts up to n numbers, so an add costs O(n). It is quick in practice, but it still grows linearly with the data.

Best method

The median depends only on the middle one or two numbers, so keep the numbers in two halves around the middle. A max-heap holds the lower half, with its largest number at the root. A min-heap holds the upper half, with its smallest number at the root. Keep the lower half equal in size to the upper half, or larger by one. Every number in the lower half is at most every number in the upper half, so the middle numbers are the two roots. To add a number, push it into the lower half, move the lower root to the upper half, and if the upper half is now larger, move its root back. A median call reads the lower root when the count is odd, and the average of both roots when it is even.

Hand trace

Run on the calls of example 1. Add 6: lower [6], upper []. Add 2: lower [2], upper [6]. Median: the count is even, so (2 + 6) / 2 = 4.0. Add 10: lower [2, 6], upper [10]. Median: the count is odd, so the lower root, 6.0. Add 3: lower [2, 3], upper [6, 10]. Median: (3 + 6) / 2 = 4.5. The result is [4.0, 6.0, 4.5].

Code

import heapq
class MedianTracker:
    def __init__(self):
        self.low = []                   # max-heap (negated): the lower half
        self.high = []                  # min-heap: the upper half
    def add(self, num):
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))
    def median(self):
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2

Time and memory

O(log n) time per add, because it does at most three heap steps. O(1) time per median, because it reads the roots. O(n) memory for all numbers.

Common mistakes

  • Using two min-heaps. The lower half needs its largest number at the root. Store negated numbers in Python's heapq to get a max-heap.
  • Letting the halves drift apart in size. Rebalance after every add, so the lower half stays equal or one larger. Balanced sizes are not enough: a large number must pass through the other half, or it can sit in the lower heap and the roots stop being the middle.
  • Returning an integer when the count is even. The average of two numbers can end in .5, so use true division.
  • Adding the two roots as 32-bit ints. 1e9 + 1e9 overflows; widen to a 64-bit int or a double before you add.

Related problems

More Heap / Priority Queue problems
Find Median From Data Stream: walkthrough and solution