📖 Scenario: Imagine you are building a system that receives numbers one by one, like scores from a game played live. You want to find the middle score (median) at any time quickly.
🎯 Goal: Build a program that keeps track of the median of numbers as they come in, using two heaps (priority queues) to organize the data efficiently.
📋 What You'll Learn
Use two heaps: a max-heap for the lower half of numbers and a min-heap for the upper half.
Balance the heaps so their sizes differ by at most one.
Insert numbers one by one and update the median after each insertion.
Print the median after all insertions.
💡 Why This Matters
🌍 Real World
Finding the median in real-time data streams like live sensor data, stock prices, or game scores.
💼 Career
Useful for roles in data engineering, real-time analytics, and software development involving streaming data.
Progress0 / 4 steps
1
Create two heaps for storing numbers
Create a max-heap called lower and a min-heap called higher using priority_queue in C++.
DSA C++
Hint
Use std::priority_queue<int> for max-heap and std::priority_queue<int, std::vector<int>, std::greater<int>> for min-heap.
2
Add a vector of numbers and a function to insert numbers
Create a vector called numbers with these values: {5, 15, 1, 3}. Then write a function called addNumber that takes an int num and inserts it into the correct heap (lower or higher) based on its value.
DSA C++
Hint
Insert num into lower if it is smaller or equal to the max of lower, else into higher.
3
Balance the heaps and process all numbers
Write a function called balanceHeaps that keeps the size difference between lower and higher at most 1 by moving elements between them. Then, in main, use a for loop to add each number from numbers using addNumber, call balanceHeaps after each insertion.
DSA C++
Hint
Move the top element from the bigger heap to the smaller heap if size difference is more than 1.
4
Calculate and print the median after all insertions
Write a function called getMedian that returns a double median based on the sizes of lower and higher. Then, in main, after processing all numbers, print the median using std::cout.
DSA C++
Hint
If both heaps have the same size, median is average of their tops. Otherwise, median is top of the bigger heap.
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 find the median by balancing smaller and larger halves of the data
B. To sort the entire data stream in ascending order
C. To store all elements in one heap for quick access
D. To remove duplicate elements 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 how median is found
Balancing these heaps allows quick access to the middle values, enabling efficient median calculation.
Final Answer:
To efficiently find the median by balancing smaller and larger halves of the data -> Option A
Quick Check:
Two heaps balance halves = median found fast [OK]
Hint: Two heaps split data into halves for median [OK]
Common Mistakes:
Thinking heaps sort entire data
Using one heap only
Confusing heaps with arrays
2. Which of the following is the default way to declare a max-heap in C++ using the priority_queue?
easy
A. priority_queue maxHeap;
B. priority_queue<int> maxHeap;
C. priority_queue maxHeap;
D. priority_queue maxHeap;
Solution
Step 1: Recall default priority_queue behavior
By default, priority_queue in C++ is a max-heap using less<int>.
Step 2: Identify correct declaration
Declaring priority_queue<int> maxHeap; creates a max-heap without extra parameters.
Final Answer:
priority_queue<int> maxHeap; -> Option B
Quick Check:
Default priority_queue = max-heap [OK]
Hint: Default priority_queue is max-heap [OK]
Common Mistakes:
Using greater<int> for max-heap
Omitting vector container
Confusing max-heap with min-heap syntax
3. Consider the following C++ code snippet that inserts numbers into two heaps to find the median:
A. The heaps are not declared correctly for median calculation
B. The comparison operator in if condition should be num >= maxHeap.top()
C. The balancing condition for maxHeap is incorrect; it should check if maxHeap.size() > minHeap.size() + 1
D. The function does not insert elements into any heap
Solution
Step 1: Analyze balancing conditions
The code moves element from maxHeap to minHeap if maxHeap.size() > minHeap.size(), but it should only do so if maxHeap.size() > minHeap.size() + 1 to keep heaps balanced properly.
Step 2: Confirm correct balancing logic
Proper balancing ensures size difference is at most 1. The current condition causes unnecessary moves, breaking balance.
Final Answer:
The balancing condition for maxHeap is incorrect; it should check if maxHeap.size() > minHeap.size() + 1 -> Option C
Quick Check:
Balance heaps only if size difference > 1 [OK]
Hint: Balance heaps only if size difference > 1 [OK]
Common Mistakes:
Wrong balancing condition
Swapping heap roles
Incorrect comparison operators
5. You are given a stream of integers: [5, 15, 1, 3, 8, 7, 9, 10, 6, 11]. Using two heaps to find the median after each insertion, what is the median after inserting all elements?
hard
A. 8
B. 7
C. 6.5
D. 7.5
Solution
Step 1: Insert elements and balance heaps step-by-step
After processing the entire stream with proper insertion (to maxHeap if <= max.top or empty, else minHeap) and balancing (rebalance if max.size > min.size + 1 or min.size > max.size), final state: maxHeap size=5 (top=7), minHeap size=5 (top=8).
Step 2: Calculate final median
After all insertions, maxHeap size = 5, minHeap size = 5, median = average of tops: (7 + 8) / 2 = 7.5
Final Answer:
7.5 -> Option D
Quick Check:
Median after all insertions = 7.5 [OK]
Hint: Median = average of two heap tops if equal size [OK]
Common Mistakes:
Not balancing heaps after each insertion
Calculating median from wrong heap
Forgetting to average when heaps equal size
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.