Median from Data Stream
The Median from Data Stream problem is an important application of heaps. It teaches us how to continuously calculate the median while numbers are being inserted one by one. Instead of sorting all the numbers again after every insertion, we use two heaps to maintain the median efficiently.
1. What Is a Data Stream?
A data stream is a sequence of values that arrives one at a time. We do not necessarily receive all the values at once. New values may continue arriving while we are processing the previous ones.
For example, imagine receiving the following numbers one by one:
Incoming numbers:
10 → 20 → 30 → 40 → 50
After receiving each number, we may need to calculate the median of all the numbers received so far.
This is different from a normal array problem because we cannot always assume that all the elements are available before processing begins.
2. What Is the Median?
The median is the middle value of a collection of numbers after they have been arranged in ascending order.
There are two important cases:
Case 1: Odd Number of Elements
If the number of elements is odd, the median is the middle element after sorting.
Example:
Numbers: 5, 1, 9
Sorted: 1, 5, 9
Median: 5
Case 2: Even Number of Elements
If the number of elements is even, the median is the average of the two middle elements.
Example:
Numbers: 4, 2, 8, 6
Sorted: 2, 4, 6, 8
Middle elements: 4 and 6
Median: (4 + 6) / 2 = 5
3. Understanding the Median from Data Stream Problem
In this problem, numbers arrive one by one. After every insertion, we must be able to return the median of all numbers received so far.
For example, consider this incoming stream:
Incoming stream: 5, 15, 1, 3
After inserting 5, the median is 5.
After inserting 15, the median is (5 + 15) / 2 = 10.
After inserting 1, the median is 5.
After inserting 3, the median is (3 + 5) / 2 = 4.
A straightforward approach would be to store all numbers, sort them after every insertion, and then find the middle element or elements. However, repeatedly sorting the complete collection can be expensive.
We can solve this problem more efficiently using two heaps.
4. Why Do We Need Two Heaps?
To calculate the median efficiently, we divide the numbers into two groups:
- Lower half: Contains the smaller half of the numbers.
- Upper half: Contains the larger half of the numbers.
We use two different heaps to manage these groups.
Max Heap for the Lower Half
A max heap stores the smaller half of the numbers. Its largest element is available at the top.
This largest element is important because it is the biggest value belonging to the lower half.
Min Heap for the Upper Half
A min heap stores the larger half of the numbers. Its smallest element is available at the top.
This smallest element is important because it is the smallest value belonging to the upper half.
Example: Suppose the numbers are 1, 3, 5, 7, 9.
Max Heap – Lower Half: 1, 3, 5
Top element = 5
Min Heap – Upper Half: 7, 9
Top element = 7
Median = 5
5. Important Rules for Maintaining Two Heaps
We must maintain two important conditions while inserting numbers.
Rule 1: Maintain the Size Difference
The number of elements in the two heaps should be equal, or one heap should contain exactly one more element than the other.
- The max heap may contain the same number of elements as the min heap.
- The max heap may contain one extra element.
We choose the max heap to contain the extra element when the total number of values is odd.
Rule 2: Maintain the Correct Ordering
Every element in the max heap must be less than or equal to every element in the min heap.
6. How to Insert a New Number
We follow a simple process whenever a new number arrives.
- Insert the new number into the max heap.
- Move the largest element from the max heap to the min heap.
- If the min heap becomes larger than the max heap, move its smallest element back to the max heap.
This process keeps the ordering and size conditions valid.
7. How to Find the Median
Once both heaps are balanced, finding the median becomes very simple.
When Both Heaps Have Equal Size
The total number of elements is even. The median is the average of the top elements of both heaps.
median = (maxHeap.top() + minHeap.top()) / 2.0;
When Max Heap Has One Extra Element
The total number of elements is odd. The median is the top element of the max heap.
median = maxHeap.top();
8. Complete Dry Run
Let us process the incoming stream:
Stream: 5, 15, 1, 3, 8
We will maintain a max heap for the lower half and a min heap for the upper half.
| Inserted Number | Max Heap (Lower Half) | Min Heap (Upper Half) | Median |
|---|---|---|---|
| 5 | 5 | Empty | 5 |
| 15 | 5 | 15 | 10 |
| 1 | 5, 1 | 15 | 5 |
| 3 | 3, 1 | 5, 15 | 4 |
| 8 | 5, 3, 1 | 8, 15 | 5 |
Step-by-Step Explanation
Step 1: Insert 5
- Insert 5 into the max heap.
- Max heap contains 5.
- Median = 5.
Step 2: Insert 15
- Insert 15 into the max heap.
- Move the largest value, 15, into the min heap.
- Both heaps contain one element.
- Median = (5 + 15) / 2 = 10.
Step 3: Insert 1
- Insert 1 into the max heap.
- Move the largest value, 5, into the min heap.
- The min heap becomes larger, so move its smallest value, 5, back into the max heap.
- Max heap contains 5 and 1; min heap contains 15.
- Median = 5.
Step 4: Insert 3
- Insert 3 into the max heap.
- Move the largest value, 5, into the min heap.
- Both heaps now contain two elements.
- Median = (3 + 5) / 2 = 4.
Step 5: Insert 8
- Insert 8 into the max heap.
- Move the largest value, 8, into the min heap.
- Move the smallest value of the min heap, 5, back into the max heap.
- Max heap contains 5, 3, 1; min heap contains 8, 15.
- Median = 5.
Output: 5, 10, 5, 4, 5
9. C++ Implementation Using Two Heaps
C++ provides the priority_queue data structure, which can be used to implement both max heaps and min heaps.
Complete Code
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class MedianFinder {
private:
// Max heap stores the lower half
priority_queue<int> maxHeap;
// Min heap stores the upper half
priority_queue<int, vector<int>, greater<int>> minHeap;
public:
// Insert a new number
void addNum(int num) {
// Insert into max heap
maxHeap.push(num);
// Move the largest element to min heap
minHeap.push(maxHeap.top());
maxHeap.pop();
// Balance the sizes
if (minHeap.size() > maxHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
// Find the current median
double findMedian() {
// Odd number of elements
if (maxHeap.size() > minHeap.size()) {
return maxHeap.top();
}
// Even number of elements
return (maxHeap.top() + minHeap.top()) / 2.0;
}
};
int main() {
MedianFinder mf;
vector<int> nums = {5, 15, 1, 3, 8};
for (int num : nums) {
mf.addNum(num);
cout << "Median: "
<< mf.findMedian() << endl;
}
return 0;
}
Output
Median: 5
Median: 10
Median: 5
Median: 4
Median: 5
10. Understanding the C++ Code
Creating the Max Heap
priority_queue<int> maxHeap;
By default, C++ priority_queue creates a max heap. The largest element is always available at the top.
Creating the Min Heap
priority_queue<int, vector<int>, greater<int>> minHeap;
The greater comparator changes the priority queue into a min heap. Its smallest element is always available at the top.
Inserting an Element
maxHeap.push(num);
We first insert the new number into the max heap.
Moving the Largest Element
minHeap.push(maxHeap.top());
maxHeap.pop();
We move the largest element from the lower half into the upper half. This helps maintain the correct ordering between the two heaps.
Balancing the Heaps
if (minHeap.size() > maxHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
If the min heap contains more elements than the max heap, we move its smallest element back into the max heap.
Calculating the Median
if (maxHeap.size() > minHeap.size()) {
return maxHeap.top();
}
return (maxHeap.top() + minHeap.top()) / 2.0;
If the max heap has one extra element, its top is the median. Otherwise, the median is the average of the two heap tops.
11. Time and Space Complexity
Let N represent the total number of numbers inserted into the data stream.
| Operation | Time Complexity | Explanation |
|---|---|---|
| Insert a number | O(log N) | Heap insertion and removal operations take logarithmic time. |
| Find median | O(1) | We directly access the top elements of both heaps. |
| Store all numbers | O(N) | Both heaps together store all inserted numbers. |
Time Complexity
Each insertion performs a constant number of heap operations. Every heap insertion or removal takes O(log N) time.
Therefore, the time complexity of inserting one number is:
O(log N)
Finding the median requires only reading the top elements of the heaps. Therefore:
O(1)
Space Complexity
All inserted numbers are stored across the two heaps. Therefore, the total space complexity is:
O(N)
12. Brute Force Approach vs Two Heaps
Before learning the two-heaps approach, it is useful to understand why repeatedly sorting the numbers is less efficient.
| Feature | Brute Force | Two Heaps |
|---|---|---|
| Insertion | Store the new number and sort again | Insert using heap operations |
| Median retrieval | After sorting, access the middle | Read the heap top elements |
| Insertion and preparation | O(N log N) per update if sorting all values | O(log N) per update |
| Median retrieval after preparation | O(1) | O(1) |
| Extra storage | O(N) | O(N) |
The two-heaps approach is more efficient when numbers arrive continuously and the median must be available after every insertion.
13. Common Mistakes to Avoid
- Using two max heaps: We need a max heap for the lower half and a min heap for the upper half.
- Ignoring heap sizes: The heaps must have equal sizes or the max heap must have exactly one extra element.
- Ignoring ordering: The largest value in the lower half must not be greater than the smallest value in the upper half.
- Using integer division: Use 2.0 when calculating the average so that decimal medians are preserved.
- Assuming the median is always one heap's top: For an even number of elements, the median is the average of both heap tops.
- Forgetting the empty case: The median cannot be calculated before any number has been inserted. In this implementation, call findMedian only after addNum has been called.
14. Applications of Median from Data Stream
The ability to calculate a median while values arrive continuously is useful in many real-world situations.
- Financial data: Finding the median of continuously arriving stock prices or transaction values.
- Monitoring systems: Tracking the median response time of servers.
- Sensor networks: Calculating the median of continuously received temperature or pressure readings.
- Online analytics: Understanding the middle value of data received from users or applications.
- Performance monitoring: Studying typical system performance without repeatedly sorting all measurements.
15. Important Interview Questions
Q1. What is the median?
The median is the middle value after arranging the numbers in sorted order. For an even number of values, it is the average of the two middle values.
Q2. Why are two heaps used in this problem?
Two heaps divide the numbers into a lower half and an upper half. Their top elements allow us to calculate the median without sorting the complete collection repeatedly.
Q3. Which heap stores the smaller half?
The max heap stores the smaller half because its largest element is available at the top.
Q4. Which heap stores the larger half?
The min heap stores the larger half because its smallest element is available at the top.
Q5. What is the time complexity of inserting a new number?
O(log N), because insertion and removal operations in a heap take logarithmic time.
Q6. What is the time complexity of finding the median?
O(1), because we only access the top elements of the heaps.
Q7. What happens when the total number of elements is even?
The heaps have equal sizes. The median is the average of the top elements of the max heap and min heap.
Q8. What happens when the total number of elements is odd?
The max heap contains one extra element. Its top element is the median.
16. Practice Problems
- Insert the numbers 2, 4, 6, 8, 10 one by one and calculate the median after every insertion.
- Insert the numbers 10, 20, 30, 40 and calculate the median after every insertion.
- Implement the MedianFinder class using a max heap and a min heap.
- Modify the implementation to handle negative numbers and duplicate values.
- Explain why repeatedly sorting the complete data collection is inefficient for a continuous stream.
17. Quick Revision
- A data stream provides numbers one at a time.
- The median is the middle value in sorted order.
- For an odd number of elements, the median is the middle element.
- For an even number of elements, the median is the average of the two middle elements.
- A max heap stores the smaller half of the numbers.
- A min heap stores the larger half of the numbers.
- The max heap can contain one more element than the min heap.
- Insertion takes O(log N) time.
- Finding the median takes O(1) time.
- The total space complexity is O(N).