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 can be found quickly by looking at the tops of the 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 is either the top of one heap or the average of the tops of both heaps.
Click to reveal answer
intermediate
How do you insert a new number into the two heaps when maintaining the median?
Compare the new number with the max heap's top. If smaller or equal, add to max heap; else add to min heap. Then rebalance the heaps if needed.
Click to reveal answer
intermediate
What is the time complexity of adding a number and finding the median using two heaps?
Adding a number takes O(log n) due to heap insertion. Finding the median is O(1) because it uses the top elements of heaps.
Click to reveal answer
intermediate
Explain why a max heap is used for the smaller half and a min heap for the larger half in this approach.
The max heap keeps the largest of the smaller half at the top, and the min heap keeps the smallest of the larger half at the top. This arrangement makes it easy to find the median by comparing these two values.
Click to reveal answer
What data structures are used to find the median in a data stream using the two heaps method?
AMax heap and min heap
BTwo max heaps
CTwo min heaps
DQueue and stack
✗ Incorrect
The method uses a max heap for the smaller half and a min heap for the larger half of the numbers.
When adding a new number, if it is smaller than the max heap's top, where should it be added?
AMin heap
BDiscard it
CEither heap
DMax heap
✗ Incorrect
Numbers smaller than or equal to the max heap's top belong to the smaller half, so they go into the max heap.
What do you do if the two heaps differ in size by more than one after insertion?
ARemove elements from both heaps
BRebalance by moving the top element from the larger heap to the smaller heap
CIgnore the size difference
DClear both heaps
✗ Incorrect
Rebalancing keeps the heaps balanced by moving the top element from the bigger heap to the smaller one.
How do you find the median when both heaps have the same size?
AAverage of tops of both heaps
BTop of max heap
CTop of min heap
DSum of all elements
✗ Incorrect
When heaps are equal in size, the median is the average of the two top elements.
What is the time complexity to find the median after adding numbers using two heaps?
AO(n)
BO(log n)
CO(1)
DO(n log n)
✗ Incorrect
Finding the median is O(1) because it only involves looking at the top elements of the heaps.
Describe the process of maintaining two heaps to find the median of a data stream.
Think about how to split numbers and keep heaps balanced.
You got /5 concepts.
Explain why balancing the two heaps is important when finding the median in a data stream.
Consider what happens if heaps are unbalanced.
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 efficiently keep track of the lower half and upper half of the numbers for median calculation
B. To sort all numbers in ascending order
C. To store all numbers in one data structure
D. To remove duplicates from 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 A
Quick Check:
Two heaps split data halves = efficient median [OK]
Hint: Two heaps split data halves for quick median [OK]
Common Mistakes:
Thinking heaps sort all data fully
Using one heap only
Confusing heaps with arrays
2. Which of the following Python code snippets correctly initializes the two heaps for the Median of Data Stream problem?
easy
A. max_heap = heapq.heapify([])
min_heap = heapq.heapify([])
C. max_heap = [] # will store negative values for max heap behavior
min_heap = []
D. max_heap = heapq.heapify([])
min_heap = []
Solution
Step 1: Understand heap initialization in Python
Python's heapq module only supports min heaps, so to simulate a max heap, we store negative values in a list.
Step 2: Check code correctness
max_heap = [] # will store negative values for max heap behavior
min_heap = [] correctly initializes empty lists for both heaps; max heap will store negative values to simulate max heap behavior.
Final Answer:
max_heap = [] # will store negative values for max heap behavior
min_heap = [] -> Option C
Quick Check:
Empty lists + negative values = max heap simulation [OK]
Hint: Use negative values in list for max heap in Python [OK]
Common Mistakes:
Calling heapq.heapify on empty list returns None
Trying to create max heap directly
Confusing heapq.heapify return value
3. Given the following code snippet, what will be the output after inserting the numbers 5, 15, 1, 3 in order and then calling get_median()?
import heapq
class MedianFinder:
def __init__(self):
self.max_heap = []
self.min_heap = []
def add_num(self, num):
if not self.max_heap or num <= -self.max_heap[0]:
heapq.heappush(self.max_heap, -num)
else:
heapq.heappush(self.min_heap, num)
if len(self.max_heap) > len(self.min_heap) + 1:
heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap))
elif len(self.min_heap) > len(self.max_heap):
heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap))
def get_median(self):
if len(self.max_heap) > len(self.min_heap):
return float(-self.max_heap[0])
else:
return (-self.max_heap[0] + self.min_heap[0]) / 2
finder = MedianFinder()
for number in [5, 15, 1, 3]:
finder.add_num(number)
print(finder.get_median())
After all insertions, median is 4.0 as heaps are balanced and median is average of tops.
Final Answer:
4.0 -> Option D
Quick Check:
Median after 4 inserts = 4.0 [OK]
Hint: Balance heaps and average tops for even count [OK]
Common Mistakes:
Not balancing heaps after insertion
Forgetting to invert max heap values
Calculating median incorrectly for even count
4. The following code snippet is intended to add a number to the MedianFinder class but contains a bug. What is the bug?
def add_num(self, num):
if not self.max_heap or num < -self.max_heap[0]:
heapq.heappush(self.max_heap, -num)
else:
heapq.heappush(self.min_heap, num)
if len(self.max_heap) > len(self.min_heap):
heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap))
elif len(self.min_heap) > len(self.max_heap) + 1:
heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap))
medium
A. The balancing conditions are reversed; max_heap can grow too large
B. The comparison should be <= instead of < in the first if condition
C. The heaps are not initialized before use
D. The code uses min heap for max_heap without negation
Solution
Step 1: Analyze balancing conditions
The code moves elements when max_heap size > min_heap size, but it should allow max_heap to be larger by at most 1.
Step 2: Identify correct balancing logic
Correct logic: if max_heap size > min_heap size + 1, move element to min_heap; if min_heap size > max_heap size, move element to max_heap.
Final Answer:
The balancing conditions are reversed; max_heap can grow too large -> Option A
Quick Check:
Balance heaps with correct size difference [OK]
Hint: Max heap can be bigger by only 1 element [OK]
Common Mistakes:
Swapping balancing conditions
Not allowing max_heap to be bigger by one
Incorrect comparison operators
5. You want to extend the MedianFinder to support removing numbers from the data stream while still efficiently calculating the median. Which data structure modification is best to support this feature?
hard
A. Keep using two heaps and rebuild them after each removal
B. Use balanced binary search trees (like AVL or Red-Black trees) instead of heaps
C. Use a single sorted list and binary search for insertion and removal
D. Use hash maps to store counts and ignore heaps
Solution
Step 1: Understand removal challenges with heaps
Heaps do not support efficient arbitrary removal; rebuilding heaps after each removal is costly.
Step 2: Identify suitable data structure
Balanced binary search trees support insertion, removal, and median retrieval in O(log n) time.
Step 3: Compare other options
Sorted lists have O(n) removal; hash maps do not maintain order; rebuilding heaps is inefficient.
Final Answer:
Use balanced binary search trees (like AVL or Red-Black trees) instead of heaps -> Option B
Quick Check:
Balanced BSTs support fast insert/remove/median [OK]
Hint: Balanced trees allow fast insert and remove [OK]
Common Mistakes:
Assuming heaps support fast removal
Using sorted lists with slow removal
Ignoring order maintenance
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.