Skip to main content
39

Find Median from Data Stream

Hardheapdesign

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Heap / Priority QueueRead the beginner guide

Implement the class MedianFinder, which receives numbers one at a time and can report their median at any moment:

  • new MedianFinder() starts with no numbers.
  • addNum(num) adds an integer.
  • findMedian() returns the median of all numbers added so far. Answers within 10^-5 of the real median are accepted.

Understand the problem

  • The median is the middle value once the numbers are sorted. For [2, 3, 4] it's 3.
  • If there's an even count, there are two middle values, and the median is their average. For [2, 3] it's 2.5.
  • The numbers arrive one at a time (a "data stream"), in any order, and findMedian can be called between any two additions. So the work must be fast for every call, not just once at the end.

Example 1

text
ops:      ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
args:     [[],             [1],      [2],      [],           [3],      []]
expected: [null,           null,     null,     1.5,          null,     2]
  • After adding 1 and 2: sorted [1, 2], two middle values, median (1 + 2) / 2 = 1.5.
  • After adding 3: sorted [1, 2, 3], median 2.

How the tests work: each test is a sequence of calls. ops names each call (the first creates the object), args holds the arguments, and expected the return values.

Constraints

  • -10^5 <= num <= 10^5
  • findMedian is only called after at least one addNum.
  • At most 5 * 10^4 calls in total.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Keep the smaller half of the numbers in a max-heap and the larger half in a min-heap, balanced in size, so the median is always sitting at the top of one or both heaps.

    The naive approach (and why it's slow)

    Keep all the numbers in a sorted array. findMedian just reads the middle: O(1). But addNum must insert the number in the right place, which shifts every element after it: O(n) per call. With 50,000 calls, that's around a billion moves.

    What's a heap?

    A heap is a structure that always knows its top item:

    • a min-heap gives you its smallest item instantly, and
    • a max-heap gives you its largest item instantly.

    Adding an item or removing the top takes O(log n). It does this without fully sorting everything: it only keeps enough order to know the top. (The beginner guide shows how it works inside.)

    The key insight

    To find the median you don't need everything sorted. You only need the one or two values in the middle. So split the numbers into two halves:

    • low holds the smaller half, in a max-heap. Its top is the largest of the small numbers.
    • high holds the larger half, in a min-heap. Its top is the smallest of the large numbers.
    text
    sorted:   1  2  3  |  4  5
              └─ low ─┘   └ high ┘
              top of low = 3    top of high = 4

    Keep two rules:

    1. Everything in low is <= everything in high.
    2. The sizes are equal, or low has one more.

    Then the two middle values are exactly the two tops:

    • odd count: the median is low's top.
    • even count: the median is (low's top + high's top) / 2.

    Adding a number while keeping the rules:

    1. Push it into low.
    2. Move low's top (its largest) into high. This fixes rule 1: if the new number was too big for the small half, it's now on the large side.
    3. If high is now bigger than low, move high's top (its smallest) back into low. This fixes rule 2.

    Step by step

    Example 1:

    Actionlow (max-heap)high (min-heap)Median
    addNum(1): push 1 to low, move 1 to high, high is bigger so move 1 back[1][]
    addNum(2): push 2 to low, move 2 to high[1][2]
    findMedian()top 1top 2(1 + 2) / 2 = 1.5
    addNum(3): push 3 to low, move 3 to high, high is bigger so move 2 back[2, 1][3]
    findMedian()top 2odd count → 2

    The code

    The reference solution is below, with comments on every important line.

    • Python: heapq only provides a min-heap. To get a max-heap, store numbers negated (-num): the smallest negated value is the largest original.
    • JavaScript/TypeScript: there's no built-in heap, so the solution includes a small one. It's an array where the item at index i has children at 2i + 1 and 2i + 2. push adds at the end and "bubbles up" while it beats its parent; pop moves the last item to the top and "sinks" it down. Being able to write this is a common expectation in JavaScript interviews.

    How fast is it?

    • addNum: O(log n), a few heap pushes and pops.
    • findMedian: O(1), just reading the tops.
    • Memory: O(n) to store all the numbers.

    Common mistakes

    • Putting the new number straight into the "right" heap by comparing. It can work, but it's easy to get wrong. The "push to low, move the top to high, rebalance" routine is always correct.
    • Integer division for the even case. The answer can be 1.5: make sure you divide as a decimal (in Python, / not //).
    • Forgetting to negate back in Python when reading low's top.

    Going deeper

    • Two heaps for "the middle" is a reusable pattern: sliding window median, or balancing two groups as items arrive.
    • Follow-up: if all numbers are between 0 and 100, a simple array of 101 counters is even faster: count each value, and walk the counters to find the middle.

    Reference solution

    js
    /**
     * A binary heap stored in an array: the item at index i has children at 2i + 1 and 2i + 2.
     * `before(a, b)` is true when `a` belongs closer to the top.
     */
    class Heap {
      items = []
    
      constructor(before) {
        this.before = before
      }
    
      get size() {
        return this.items.length
      }
    
      peek() {
        return this.items[0]
      }
    
      push(value) {
        const items = this.items
        items.push(value) // add at the end...
        let i = items.length - 1
        // ...then bubble it up while it beats its parent.
        while (i > 0) {
          const parent = (i - 1) >> 1
          if (!this.before(items[i], items[parent])) break
          ;[items[i], items[parent]] = [items[parent], items[i]]
          i = parent
        }
      }
    
      pop() {
        const items = this.items
        const top = items[0] // the item we'll return
        const last = items.pop()
        if (items.length > 0) {
          // Move the last item to the top, then sink it down to where it belongs.
          items[0] = last
          let i = 0
          while (true) {
            const left = 2 * i + 1
            const right = left + 1
            let best = i // whichever of node, left child, right child belongs on top
            if (left < items.length && this.before(items[left], items[best])) best = left
            if (right < items.length && this.before(items[right], items[best])) best = right
            if (best === i) break
            ;[items[i], items[best]] = [items[best], items[i]]
            i = best
          }
        }
        return top
      }
    }
    
    export default class MedianFinder {
      low = new Heap((a, b) => a > b) // max-heap: the smaller half, its top is its largest
      high = new Heap((a, b) => a < b) // min-heap: the larger half, its top is its smallest
    
      /**
       * @param {number} num
       * @return {void}
       */
      addNum(num) {
        this.low.push(num)
        // Move the largest of the small half across: now everything in low <= everything in high.
        this.high.push(this.low.pop())
        // Keep the sizes balanced, with low allowed one extra.
        if (this.high.size > this.low.size) this.low.push(this.high.pop())
      }
    
      /**
       * @return {number}
       */
      findMedian() {
        // Odd count: the middle value is low's top.
        if (this.low.size > this.high.size) return this.low.peek()
        // Even count: average the two middle values.
        return (this.low.peek() + this.high.peek()) / 2
      }
    }
    ts
    /**
     * A binary heap stored in an array: the item at index i has children at 2i + 1 and 2i + 2.
     * `before(a, b)` is true when `a` belongs closer to the top.
     */
    class Heap {
      private items: number[] = []
    
      constructor(private before: (a: number, b: number) => boolean) {}
    
      get size(): number {
        return this.items.length
      }
    
      peek(): number {
        return this.items[0]
      }
    
      push(value: number): void {
        const items = this.items
        items.push(value) // add at the end...
        let i = items.length - 1
        // ...then bubble it up while it beats its parent.
        while (i > 0) {
          const parent = (i - 1) >> 1
          if (!this.before(items[i], items[parent])) break
          ;[items[i], items[parent]] = [items[parent], items[i]]
          i = parent
        }
      }
    
      pop(): number {
        const items = this.items
        const top = items[0] // the item we'll return
        const last = items.pop()!
        if (items.length > 0) {
          // Move the last item to the top, then sink it down to where it belongs.
          items[0] = last
          let i = 0
          while (true) {
            const left = 2 * i + 1
            const right = left + 1
            let best = i // whichever of node, left child, right child belongs on top
            if (left < items.length && this.before(items[left], items[best])) best = left
            if (right < items.length && this.before(items[right], items[best])) best = right
            if (best === i) break
            ;[items[i], items[best]] = [items[best], items[i]]
            i = best
          }
        }
        return top
      }
    }
    
    export default class MedianFinder {
      private low = new Heap((a, b) => a > b) // max-heap: the smaller half, its top is its largest
      private high = new Heap((a, b) => a < b) // min-heap: the larger half, its top is its smallest
    
      addNum(num: number): void {
        this.low.push(num)
        // Move the largest of the small half across: now everything in low <= everything in high.
        this.high.push(this.low.pop())
        // Keep the sizes balanced, with low allowed one extra.
        if (this.high.size > this.low.size) this.low.push(this.high.pop())
      }
    
      findMedian(): number {
        // Odd count: the middle value is low's top.
        if (this.low.size > this.high.size) return this.low.peek()
        // Even count: average the two middle values.
        return (this.low.peek() + this.high.peek()) / 2
      }
    }
    python
    import heapq
    
    
    class MedianFinder:
        def __init__(self):
            # heapq is a min-heap only. Storing -num turns it into a max-heap.
            self.low = []  # max-heap of the smaller half, stored negated
            self.high = []  # min-heap of the larger half
    
        def add_num(self, num: int) -> None:
            heapq.heappush(self.low, -num)
            # Move the largest of the small half across: now everything in low <= everything in high.
            heapq.heappush(self.high, -heapq.heappop(self.low))
            # Keep the sizes balanced, with low allowed one extra.
            if len(self.high) > len(self.low):
                heapq.heappush(self.low, -heapq.heappop(self.high))
    
        def find_median(self) -> float:
            # Odd count: the middle value is low's top (negate it back).
            if len(self.low) > len(self.high):
                return -self.low[0]
            # Even count: average the two middle values.
            return (-self.low[0] + self.high[0]) / 2