What is the main idea behind using two heaps to find the median of a data stream?
Use a max heap to store the smaller half of numbers and a min heap to store the larger half. This way, the median is either the top of one heap or the average of the tops of both heaps.
Click to reveal answer
beginner
Why do we balance the sizes of the two heaps when finding the median?
Balancing ensures that the heaps differ in size by at most one, so the median can be found easily from the top elements of the heaps.
Click to reveal answer
beginner
In the two heaps approach, which heap stores the smaller half of the numbers?
The max heap stores the smaller half of the numbers, so its top is the largest of the smaller half.
Click to reveal answer
beginner
How do you find the median when the total number of elements is even using two heaps?
The median is the average of the top elements of the max heap and the min heap.
Click to reveal answer
beginner
What happens when a new number is smaller than the max heap's top in the two heaps method?
The new number is added to the max heap because it belongs to the smaller half of the data.
Click to reveal answer
What data structure is used to store the larger half of numbers in the two heaps method?
AMin heap
BMax heap
CQueue
DStack
✗ Incorrect
The min heap stores the larger half of the numbers so that the smallest of the larger half is at the top.
If the max heap has 5 elements and the min heap has 3 elements, what should you do?
AMove one element from max heap to min heap
BAdd more elements to min heap
CRemove elements from min heap
DDo nothing
✗ Incorrect
The heaps should be balanced so their sizes differ by at most one. Moving one element from max heap to min heap balances them.
When the total number of elements is odd, where is the median found?
AAverage of both heaps' tops
BTop of the heap with more elements
CBottom of max heap
DBottom of min heap
✗ Incorrect
The median is the top of the heap that has one extra element.
What is the time complexity to add a number and find the median using two heaps?
AO(1)
BO(n)
CO(log n)
DO(n log n)
✗ Incorrect
Adding to a heap and balancing takes O(log n), and finding median is O(1).
Which heap's top element represents the largest number in the smaller half?
ANeither heap
BMin heap
CBoth heaps
DMax heap
✗ Incorrect
The max heap stores the smaller half, so its top is the largest number in that half.
Explain how two heaps are used to maintain the median in a data stream.
Think about splitting numbers into two groups and how to find the middle.
You got /4 concepts.
Describe the steps to add a new number to the two heaps and update the median.
Consider where the new number fits and how to keep heaps balanced.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of using two heaps (a max heap and a min heap) in the Median of Data Stream problem?
easy
A. To store all numbers in a single data structure
B. To sort all numbers in ascending order
C. To efficiently keep track of the lower half and upper half of the numbers for median calculation
D. To find the maximum number in the data stream
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 C
Quick Check:
Two heaps split data for median [OK]
Hint: Two heaps split data into halves for quick median [OK]
Common Mistakes:
Thinking heaps sort all numbers completely
Using only one heap for median
Confusing max heap and min heap roles
2. Which of the following Java code snippets correctly initializes a max heap using PriorityQueue for the Median of Data Stream problem?
easy
A. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
B. PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
C. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.naturalOrder());
D. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.naturalOrder());
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 A
Quick Check:
Max heap needs reverse order comparator [OK]
Hint: Use Collections.reverseOrder() for max heap in Java [OK]
Common Mistakes:
Using default PriorityQueue without comparator
Using naturalOrder() which is min heap
Using Collections.naturalOrder() which doesn't exist
3. Consider the following Java code snippet for adding numbers to two heaps and finding the median:
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?
medium
A. 2.5
B. 2
C. 3
D. 1
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 B
Quick Check:
Median of [1,2,5] is 2 [OK]
Hint: Median of odd count is middle element [OK]
Common Mistakes:
Calculating average instead of middle for odd count
Ignoring heap balancing
Confusing median with mean
4. The following Java method is part of a MedianFinder class using two heaps. It is supposed to add a number and rebalance heaps. Identify the bug:
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());
}
}
medium
A. Should check if maxHeap is empty before peek() to avoid NullPointerException
B. The addNum method should not add to minHeap when num equals maxHeap.peek()
C. The rebalance condition for minHeap size is incorrect; should be minHeap.size() > maxHeap.size() + 1
D. No bug, method works correctly
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 D
Quick Check:
Correct heap balancing logic [OK]
Hint: Check heap sizes differ by at most one [OK]
Common Mistakes:
Forgetting to check maxHeap empty before peek
Incorrect rebalance size conditions
Misplacing elements between heaps
5. You want to extend the MedianFinder class to handle a large data stream efficiently. Which approach improves performance when finding the median after every insertion?
hard
A. Use two balanced heaps to keep halves and rebalance after each insertion
B. Store all numbers in a list and sort it after each insertion
C. Use a single max heap to store all numbers
D. Use a hash map to count frequencies and calculate median from counts
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 A
Quick Check:
Two heaps optimize median in data stream [OK]
Hint: Two heaps give fast median updates in streams [OK]
Common Mistakes:
Sorting entire list each time
Using single heap only
Ignoring insertion cost
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.