What if you could instantly know the middle value of a never-ending list without sorting it every time?
Why Median of Data Stream Using Two Heaps in DSA Typescript?
Imagine you are tracking the middle value of a growing list of numbers, like daily temperatures or scores, but you get the numbers one by one and want to know the middle value at any time.
Doing this by sorting the whole list every time a new number arrives is like rearranging your entire bookshelf every time you get a new book--slow and tiring!
Sorting the entire list after each new number is slow because it takes more time as the list grows.
Also, manually finding the middle value each time is error-prone and wastes a lot of effort.
Using two heaps (special boxes that keep numbers in order) lets you quickly find the middle value without sorting everything again.
One heap keeps the smaller half of numbers, the other keeps the bigger half, so the middle is always easy to find.
numbers.push(newNumber); numbers.sort((a, b) => a - b); const mid = Math.floor(numbers.length / 2); const median = numbers.length % 2 === 0 ? (numbers[mid - 1] + numbers[mid]) / 2 : numbers[mid];
const maxHeap = new MaxHeap(); const minHeap = new MinHeap(); addNumber(newNumber); const median = getMedian();
This method lets you find the middle value instantly as new numbers come in, even if the list grows very large.
Streaming apps use this to show the median rating of a movie as viewers keep rating it live, without waiting for all ratings to finish.
Manually sorting each time is slow and inefficient.
Two heaps keep track of smaller and larger halves separately.
Median can be found quickly without full sorting.
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 how this helps find the median
By balancing these heaps, the median is either the top of one heap or the average of tops of both heaps.Final Answer:
To efficiently keep track of the lower half and upper half of the numbers separately -> Option CQuick Check:
Two heaps split data halves = efficient median [OK]
- Thinking heaps sort all numbers fully
- Using one heap only
- Confusing heaps with arrays
Solution
Step 1: Understand max heap comparator
Max heap comparator returns positive if first is less than second, so b - a creates max heap.Step 2: Check each option
const maxHeap = new PriorityQueue<number>((a, b) => b - a); uses (b - a) which is correct for max heap; others do not create max heap order.Final Answer:
const maxHeap = new PriorityQueue<number>((a, b) => b - a); -> Option AQuick Check:
Comparator b - a = max heap [OK]
- Using a - b for max heap (creates min heap)
- Not providing comparator
- Using addition in comparator
[5, 15, 1, 3], what is the median after all insertions using two heaps?Solution
Step 1: Insert numbers and balance heaps
Insert 5 -> maxHeap=[5] (top=5), minHeap=[]; Insert 15 -> minHeap=[15] (top=15), sizes 1:1; Insert 1 -> maxHeap=[5,1] (top=5), sizes 2:1; Insert 3 -> maxHeap=[5,3,1] (top=5), sizes 3:1 -> balance (max.size > min.size+1), move max.top=5 to minHeap -> maxHeap=[3,1] (top=3), minHeap=[5,15] (top=5), sizes 2:2.Step 2: Calculate median from heaps
Sizes equal, median = (maxHeap.top + minHeap.top)/2 = (3 + 5)/2 = 4.Final Answer:
4 -> Option BQuick Check:
Median of [5,15,1,3] = 4 [OK]
- Taking median as top of one heap only
- Not balancing heaps after insertion
- Wrong average calculation
if (num <= maxHeap.peek()) {
maxHeap.enqueue(num);
} else {
minHeap.enqueue(num);
}
// Balance heaps
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.enqueue(maxHeap.dequeue());
} else if (minHeap.size() > maxHeap.size()) {
maxHeap.enqueue(minHeap.dequeue());
}
What is the bug in this code?Solution
Step 1: Analyze peek() usage on maxHeap
If maxHeap is empty, calling peek() causes error because no element exists yet.Step 2: Identify missing empty check
Code should check if maxHeap is empty before peek() or handle initial insertion separately.Final Answer:
It does not handle empty maxHeap before peek() call -> Option DQuick Check:
Empty heap peek() causes runtime error [OK]
- Assuming heaps always have elements
- Mixing enqueue and push methods
- Balancing heaps incorrectly
Solution
Step 1: Understand removal challenge in heaps
Heaps do not support efficient arbitrary removal, so direct removal is costly.Step 2: Explain lazy removal with hash map
Mark elements as removed in a hash map and skip them during heap operations to simulate removal efficiently.Step 3: Compare other options
Balanced trees support removal but are more complex; arrays are inefficient; queues do not maintain order.Final Answer:
Use two heaps with a hash map to mark removed elements lazily -> Option AQuick Check:
Lazy removal with hash map + heaps = efficient median update [OK]
- Trying direct removal from heaps
- Using arrays causing slow operations
- Ignoring complexity of balanced trees
Ready to prove it?
Pass the test and this pattern moves unknown
