Skip to content
DSA Patterns
Menu
Language
Heap & Top KLC #2953 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Find Median from Data Stream

Problem (restated)

Support addNum(num) and findMedian() over a growing stream. Median is middle (odd) or average of two middles (even).

Intuition

Keep lower half in a max-heap, upper half in a min-heap. Balance sizes so lo has n/2 or n/2+1 elements.

Approaches

Two heaps (max + min)

Unverified
Time O(log n) add, O(1) medianSpace O(n)

Idea. Push into lo or hi by value; rebalance so lo.Count ≥ hi.Count and |lo-hi| ≤ 1. Median from peeks.

Walkthrough. add 1,2,3 → lo=[2,1] hi=[3] → median 2; add 4 → average of 2 and 3 = 2.5.

Trade-offs. Sorted list is O(n) insert; dual heap is the interview target.

Solution
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
export class MedianFinder {
  // lo is a max-heap; hi is a min-heap. Both store the actual values.
  private lo: Heap<number> = new Heap<number>((a, b) => a > b);
  private hi: Heap<number> = new Heap<number>((a, b) => a < b);

  addNum(num: number): void {
    if (this.lo.size === 0 || num <= this.lo.peek()) {
      this.lo.push(num);
    } else {
      this.hi.push(num);
    }
    if (this.lo.size > this.hi.size + 1) {
      this.hi.push(this.lo.pop());
    } else if (this.hi.size > this.lo.size) {
      this.lo.push(this.hi.pop());
    }
  }

  findMedian(): number {
    if (this.lo.size > this.hi.size) return this.lo.peek();
    return (this.lo.peek() + this.hi.peek()) / 2;
  }
}
export class MedianFinder {
  // lo is a max-heap; hi is a min-heap. Both store the actual values.
  private lo: Heap<number> = new Heap<number>((a, b) => a > b);
  private hi: Heap<number> = new Heap<number>((a, b) => a < b);

  addNum(num: number): void {
    if (this.lo.size === 0 || num <= this.lo.peek()) {
      this.lo.push(num);
    } else {
      this.hi.push(num);
    }
    if (this.lo.size > this.hi.size + 1) {
      this.hi.push(this.lo.pop());
    } else if (this.hi.size > this.lo.size) {
      this.lo.push(this.hi.pop());
    }
  }

  findMedian(): number {
    if (this.lo.size > this.hi.size) return this.lo.peek();
    return (this.lo.peek() + this.hi.peek()) / 2;
  }
}

Sorted list baseline

Unverified
Time O(n) add, O(1) medianSpace O(n)

Idea. Keep numbers sorted; binary-search the slot, then shift the tail. Median is the middle element or the mean of the two middles.

Trade-offs. The lookup is logarithmic. The shift makes each add O(n). Two heaps are the interview target.

Solution
/** Naive median: keep a sorted array (O(n) insert). */
export class MedianFinderSorted {
  private a: number[] = [];
  addNum(num: number): void {
    let lo = 0, hi = this.a.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (this.a[mid]! < num) lo = mid + 1;
      else hi = mid;
    }
    this.a.splice(lo, 0, num);
  }
  findMedian(): number {
    const n = this.a.length;
    const m = n >> 1;
    return n % 2 ? this.a[m]! : (this.a[m - 1]! + this.a[m]!) / 2;
  }
}
/** Naive median: keep a sorted array (O(n) insert). */
export class MedianFinderSorted {
  private a: number[] = [];
  addNum(num: number): void {
    let lo = 0, hi = this.a.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (this.a[mid]! < num) lo = mid + 1;
      else hi = mid;
    }
    this.a.splice(lo, 0, num);
  }
  findMedian(): number {
    const n = this.a.length;
    const m = n >> 1;
    return n % 2 ? this.a[m]! : (this.a[m - 1]! + this.a[m]!) / 2;
  }
}

Template connection

Two heaps split the stream into order statistics. The low half is a max-heap, the high half a min-heap, the sizes differ by at most 1, and every low value is ≤ every high value. An odd count reads the low top. An even count averages the two tops.

Notes

Two heaps keep the lower half (max-heap) and upper half (min-heap) balanced by size. Invariant: every value in lower ≤ every value in upper, and sizes differ by at most 1. Median is the max of lower (odd count) or average of the two roots (even). Rebalance after each insert. This is online: you never re-sort the whole stream.

Reflection

  • The low half is a max-heap and the high half a min-heap. Their sizes differ by at most 1. On an odd count the answer is the low top.
  • On an even count the answer is the mean of the two tops. Do negatives, or ties, throw the balance off?
  • One element is itself. Python’s max-heap stores negated values. Negating int.MinValue overflows in C#.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Running median. Lower half in a max-heap (lo), upper half in a min-heap (hi).

stack
∅

lo.size ≥ hi.size · |lo-hi| ≤ 1

Key:CurrentActive rangeMatchSettled