Algo-Sim › Heaps & Priority Queues

Find Median from Data Stream

Hard · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Support addNum and findMedian on a growing stream. Two heaps keep the smaller and larger halves, so the median is always at their tops.

Problem

Design a class that receives integers one at a time with addNum(num) and can report, at any moment, the median of everything added so far with findMedian(). With an even count, the median is the mean of the two middle values.

Constraints

Edge cases to test

Follow-up questions

What if all numbers are in 0..100?
Keep 101 counts and walk them to the middle: O(1) add, O(100) median.
What if you need the median of a sliding window?
Two heaps with lazy deletion, or a sorted multiset: O(log k) per step (LC 480).

Solution

Java

class MedianFinder {
    private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());
    private final PriorityQueue<Integer> high = new PriorityQueue<>();

    public void addNum(int num) {
        low.offer(num);
        high.offer(low.poll());
        if (high.size() > low.size()) {
            low.offer(high.poll());
        }
    }

    public double findMedian() {
        if (low.size() > high.size()) return low.peek();
        return (low.peek() + high.peek()) / 2.0;
    }
}

Python

import heapq


class MedianFinder:
    def __init__(self):
        self.low = []   # max-heap: values are stored negated
        self.high = []  # min-heap

    def addNum(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 findMedian(self):
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2

C++

#include <bits/stdc++.h>
using namespace std;

class MedianFinder {
  public:
    priority_queue<int> low;
    priority_queue<int, vector<int>, greater<int>> high;

    void addNum(int num) {
        low.push(num);
        high.push(low.top());
        low.pop();
        if (int(high.size()) > int(low.size())) {
            low.push(high.top());
            high.pop();
        }
    }

    double findMedian() {
        if (int(low.size()) > int(high.size()))
            return low.top();
        return (low.top() + high.top()) / 2.0;
    }
};

More Heaps & Priority Queues problems