DIGITAL GURU
Java DSA Portfolio

Find Median in Data Stream (Two Heaps)

Find running median of a data stream in O(1) time using Max-Heap (left half) & Min-Heap (right half).

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Real-World Analogy

Finding running median is like balancing a see-saw: put lower half numbers in a Max-Heap on the left, upper half in a Min-Heap on the right. The see-saw handles middle elements!

Two Heaps Pattern

Maintains two heaps: `maxHeap` for smaller lower half numbers, `minHeap` for larger upper half numbers.

Production Code Example:

MedianFinder.java
import java.util.*;
public class MedianFinder {
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
    private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    public void addNum(int num) {
        maxHeap.offer(num);
        minHeap.offer(maxHeap.poll());
        if (maxHeap.size() < minHeap.size()) maxHeap.offer(minHeap.poll());
    }
    public double findMedian() {
        return maxHeap.size() > minHeap.size() ? maxHeap.peek() : (maxHeap.peek() + minHeap.peek()) / 2.0;
    }
}

Key Complexity & Algorithmic Takeaways:

When implementing Find Median in Data Stream (Two Heaps) in coding interviews and production applications, keep these core guidelines in mind:

  • Time Complexity Analysis: Always evaluate best-case, average-case, and worst-case time complexities ($O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$).
  • Space Complexity & Memory Bounds: Account for auxiliary memory usage, call stack frame recursion overhead, and heap allocations.
  • Edge Cases & Validation: Test empty inputs, null pointers, single-element collections, duplicate values, and integer overflow bounds.
  • Optimal vs Naive Solutions: Start with a clear brute-force solution, then optimize using techniques like Hashing, Two Pointers, Windowing, or Dynamic Programming.

Summary Takeaway:

Mastering Find Median in Data Stream (Two Heaps) provides the foundational problem-solving skills needed to pass technical coding interviews at top tech companies and write ultra-performant software systems.

Time Complexity

`addNum()` runs in $O(\log N)$ time, `findMedian()` runs in $O(1)$ constant time!