
Problem
Solution
Submissions
Median from Data Stream
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the median of a data stream. The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. Implement a data structure that supports adding integers and finding the median efficiently.
Example 1
- Input: addNumber(1), addNumber(2), findMedian()
- Output: 1.5
- Explanation:
Step 1: Add 1 to the data stream: [1]
Step 2: Add 2 to the data stream: [1, 2]
Step 3: Find median of [1, 2] = (1 + 2) / 2 = 1.5
Example 2
- Input: addNumber(1), addNumber(2), addNumber(3), findMedian()
- Output: 2.0
- Explanation:
Step 1: Add 1 to the data stream: [1]
Step 2: Add 2 to the data stream: [1, 2]
Step 3: Add 3 to the data stream: [1, 2, 3]
Step 4: Find median of [1, 2, 3] = 2.0 (middle element)
Constraints
- -10^5 ≤ num ≤ 10^5
- There will be at least one element in the data structure before calling findMedian
- At most 5 * 10^4 calls will be made to addNumber and findMedian
- Time Complexity: O(log n) for addNumber, O(1) for findMedian
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two heaps: a max heap for the smaller half and a min heap for the larger half
- Keep the max heap size equal to or one more than the min heap size
- The median is either the top of max heap or average of both heap tops
- When adding a number, decide which heap to add it to based on current median
- Balance the heaps after each insertion to maintain the size property
- Use arrays to simulate heap behavior with manual heap operations