Practice Problem

Find Median from Data Stream

Difficulty: Hard

Design a data structure that efficiently finds the median from a stream of integers using two heaps.

Find Median from 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.

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

Implement the MedianFinder class:

  • MedianFinder(): Initializes the MedianFinder object.
  • addNum(num): Adds the integer num from the data stream to the data structure.
  • findMedian(): Returns the median of all elements so far. Answers within 10^-5 of the actual answer will be accepted.

Examples

Example 1:

Input:
  MedianFinder()
  addNum(1)
  addNum(2)
  findMedian() -> 1.5
  addNum(3)
  findMedian() -> 2.0

Example 2:

Input:
  MedianFinder()
  addNum(6)
  findMedian() -> 6.0
  addNum(10)
  findMedian() -> 8.0
  addNum(2)
  findMedian() -> 6.0
  addNum(6)
  findMedian() -> 6.0

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 addNum and findMedian.

Expected Complexity

  • Time: O(log n) per addNum, O(1) per findMedian
  • Space: O(n)
HARD
Heap
Min Heap
Max Heap
Priority Queue
Median Finding
Data Structures
Advanced

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium