sagelearnai

Find Median from Data Stream

Difficulty: Hard · Pattern: Heap & Priority Queue · LeetCode #295

Design MedianFinder:

  • addNum(num): add an integer from the stream,
  • findMedian(): return the median of all numbers added so far (the average of the two middle values when the count is even).

Example

text
addNum(5), addNum(15) → findMedian() = 10.0, addNum(1) → findMedian() = 5

Hints

  1. Sorting on every query is too slow. You only need the middle element(s).
  2. Split the numbers into a lower half and an upper half. Which element of each half do you need quickly?
  3. Keep the halves' sizes equal (or the lower half one bigger).

Approach

Maintain a max-heap lo (lower half) and a min-heap hi (upper half), with every value in lo ≤ every value in hi, and len(lo) equal to len(hi) or one more.

addNum: push to lo, then move lo's max to hi (this preserves the ordering), and if hi became larger, move its min back to lo. findMedian: if lo is bigger, it's lo's max; otherwise the average of both tops. O(log n) add, O(1) median.

Complexity

Time: O(log n) per add, O(1) per median. Space: O(n).

Python solution
import heapq

class MedianFinder:
    def __init__(self):
        self.lo, self.hi = [], []          # lo: max-heap via negatives, hi: min-heap

    def addNum(self, num):
        heapq.heappush(self.lo, -num)
        heapq.heappush(self.hi, -heapq.heappop(self.lo))
        if len(self.hi) > len(self.lo):
            heapq.heappush(self.lo, -heapq.heappop(self.hi))

    def findMedian(self):
        if len(self.lo) > len(self.hi):
            return -self.lo[0]
        return (-self.lo[0] + self.hi[0]) / 2
JavaScript solution
class MinHeap {
  constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
  get size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) { const a = this.a; a.push(x); let i = a.length - 1;
    while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
  pop() { const a = this.a, top = a[0], last = a.pop();
    if (a.length) { a[0] = last; let i = 0;
      for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
        if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
        if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
    return top; }
}

class MedianFinder {
  constructor() { this.lo = new MinHeap((a, b) => b - a); this.hi = new MinHeap(); }
  addNum(num) {
    this.lo.push(num);
    this.hi.push(this.lo.pop());
    if (this.hi.size > this.lo.size) this.lo.push(this.hi.pop());
  }
  findMedian() {
    return this.lo.size > this.hi.size ? this.lo.peek() : (this.lo.peek() + this.hi.peek()) / 2;
  }
}