Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›HEAP›Find Median from Data Stream
Hard

Find Median from Data Stream

heapdesigntwo-heaps

Problem

The MedianFinder class finds the median of a data stream.

Implement addNum(int num) and findMedian() returning the median of current elements.

If the count is even, the median is the mean of the two middle values.

Examples

Example 1

Input: addNum(1), addNum(2), findMedian(), addNum(3), findMedian()

Output: 1.5, 2.0

Constraints

  • •-10^5 <= num <= 10^5
  • •At most 5*10^4 calls to addNum and findMedian.

Hints

Hint 1

Two heaps: max-heap for lower half, min-heap for upper half. Balance sizes.

Solutions

class MedianFinder {
    private PriorityQueue<Integer> lower = new PriorityQueue<>(Collections.reverseOrder()); // max-heap
    private PriorityQueue<Integer> upper = new PriorityQueue<>();                            // min-heap

    public void addNum(int num) {
        lower.offer(num);          // always add to lower first
        upper.offer(lower.poll()); // rebalance: push lower's max to upper
        if (lower.size() < upper.size()) // lower should have >= upper size
            lower.offer(upper.poll());
    }

    public double findMedian() {
        if (lower.size() > upper.size()) return lower.peek();
        return (lower.peek() + upper.peek()) / 2.0;
    }
}
Java

Time: O(log n) addNum, O(1) findMedian · Space: O(n)