Tutorialspoint
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)
HeapAccentureAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize two heaps - max heap for smaller half, min heap for larger half
 Step 2: For first number, add it directly to max heap
 Step 3: For subsequent numbers, compare with max heap top to decide which heap to add to
 Step 4: After adding, balance the heaps so max heap size equals or is one more than min heap size
 Step 5: Move elements between heaps using heap operations to maintain balance
 Step 6: For median, if max heap size > min heap size, return max heap top
 Step 7: Otherwise, return average of both heap tops

Submitted Code :