Find Median from Data Stream - Problem

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.

For example:

  • For arr = [2,3,4], the median is 3
  • For arr = [2,3], the median is (2 + 3) / 2 = 2.5

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object
  • void addNum(int num) adds the integer num from the data stream to the data structure
  • double findMedian() returns the median of all elements so far

Answers within 10⁻⁵ of the actual answer will be accepted.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"], values = [null,1,2,null,3,null]
Output: [null,null,null,1.5,null,2.0]
💡 Note: Initialize finder, add 1, add 2, find median (1+2)/2=1.5, add 3, find median 2.0
Example 2 — Single Element
$ Input: operations = ["MedianFinder","addNum","findMedian"], values = [null,5,null]
Output: [null,null,5.0]
💡 Note: With only one element, the median is that element itself
Example 3 — Negative Numbers
$ Input: operations = ["MedianFinder","addNum","addNum","findMedian"], values = [null,-1,-2,null]
Output: [null,null,null,-1.5]
💡 Note: With -1 and -2, the median is (-1 + -2) / 2 = -1.5

Constraints

  • -105 ≤ num ≤ 105
  • There will be at least one element in the data structure before calling findMedian
  • At most 5 × 104 calls will be made to addNum and findMedian

Visualization

Tap to expand
Find Median from Data StreamInput Stream:addNum(1)addNum(2)findMedian()Data Structure Maintains: [1, 2]Median = (1 + 2) / 2 = 1.5Output:1.5🎯 Key: Maintain sorted halves for O(1) median access
Understanding the Visualization
1
Input Stream
Operations: addNum(1), addNum(2), findMedian()
2
Data Structure
Maintain sorted order or balanced partitions
3
Output
Return median values: 1.5
Key Takeaway
🎯 Key Insight: Two balanced heaps allow O(log n) insertions with O(1) median queries
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
78.4K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen