What if you could find the middle number instantly, no matter how many numbers keep coming in?
Why Median of Data Stream Using Two Heaps in DSA Java?
Imagine you are tracking the middle value of a long list of numbers that keeps growing, like daily temperatures or scores in a game. You try to find the middle number every time a new number arrives by sorting the entire list again and again.
Sorting the whole list every time is slow and tiresome, especially when the list grows very large. It wastes time and can make your program lag or freeze. Also, manually keeping track of the middle value is confusing and easy to mess up.
Using two heaps (one max heap and one min heap) lets you keep the smaller half of numbers in one heap and the larger half in the other. This way, you can quickly find the middle value without sorting everything again. It's like having two neat piles where you always know the top cards to find the middle.
List<Integer> numbers = new ArrayList<>();
numbers.add(newNumber);
Collections.sort(numbers);
int median = numbers.get(numbers.size() / 2);PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // Add number and rebalance heaps // Median is top of maxHeap or average of tops
This method enables fast, real-time calculation of the median in a growing stream of numbers without slowing down as data grows.
Streaming apps that show live median user ratings or financial apps that track median stock prices in real time use this technique to keep data fresh and responsive.
Manually sorting each time is slow and inefficient.
Two heaps keep data split for quick median access.
This approach works well for continuous, growing data streams.
Practice
Solution
Step 1: Understand the role of two heaps
The max heap stores the smaller half of the numbers, and the min heap stores the larger half.Step 2: Explain median calculation
By balancing these heaps, the median can be found quickly from the top elements of the heaps.Final Answer:
To efficiently keep track of the lower half and upper half of the numbers for median calculation -> Option CQuick Check:
Two heaps split data for median [OK]
- Thinking heaps sort all numbers completely
- Using only one heap for median
- Confusing max heap and min heap roles
Solution
Step 1: Identify max heap initialization
Java's PriorityQueue is a min heap by default; to make max heap, use Collections.reverseOrder().Step 2: Check options
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); uses Collections.reverseOrder(), which correctly creates a max heap.Final Answer:
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); -> Option AQuick Check:
Max heap needs reverse order comparator [OK]
- Using default PriorityQueue without comparator
- Using naturalOrder() which is min heap
- Using Collections.naturalOrder() which doesn't exist
MedianFinder mf = new MedianFinder(); mf.addNum(1); mf.addNum(5); mf.addNum(2); System.out.println(mf.findMedian());
Assuming the MedianFinder class uses two heaps correctly, what will be the printed output?
Solution
Step 1: Add numbers and balance heaps
Numbers added: 1, 5, 2. Sorted order: 1, 2, 5. Median is middle number 2.Step 2: Calculate median
Since odd count, median is the root of the heap with one extra element, which is 2.Final Answer:
2 -> Option BQuick Check:
Median of [1,2,5] is 2 [OK]
- Calculating average instead of middle for odd count
- Ignoring heap balancing
- Confusing median with mean
public void addNum(int num) {
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
maxHeap.add(num);
} else {
minHeap.add(num);
}
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.add(maxHeap.poll());
} else if (minHeap.size() > maxHeap.size()) {
maxHeap.add(minHeap.poll());
}
}Solution
Step 1: Analyze addNum logic
It adds to maxHeap if empty or num <= maxHeap.peek(), else to minHeap.Step 2: Check rebalance conditions
Rebalances if maxHeap is bigger by more than 1 or minHeap bigger than maxHeap.Final Answer:
No bug, method works correctly -> Option DQuick Check:
Correct heap balancing logic [OK]
- Forgetting to check maxHeap empty before peek
- Incorrect rebalance size conditions
- Misplacing elements between heaps
Solution
Step 1: Evaluate approaches for median calculation
Sorting after each insertion (Store all numbers in a list and sort it after each insertion) is costly (O(n log n)). Single heap or hash map do not support quick median.Step 2: Explain two heaps efficiency
Two heaps keep halves balanced, allowing O(log n) insertion and O(1) median retrieval.Final Answer:
Use two balanced heaps to keep halves and rebalance after each insertion -> Option AQuick Check:
Two heaps optimize median in data stream [OK]
- Sorting entire list each time
- Using single heap only
- Ignoring insertion cost
Ready to prove it?
Pass the test and this pattern moves unknown
