Find Median from Data Stream
Beginner Mode

Problem Statement

Design a data structure that supports adding integers from a continuous stream and retrieving the median of all integers seen so far at any point.

The median is the middle value in a sorted list of numbers. If the list has an even number of elements, the median is the average of the two middle values.

For example:

  • [3, 5, 7] has median 5
  • [3, 5] has median (3 + 5) / 2 = 4.0

Implement the MedianFinder class:

  • MedianFinder() initializes the data structure.
  • void addNum(int num) adds the integer num to the data structure.
  • float findMedian() returns the median of all elements added so far. Answers within 10^-5 of the actual answer will be accepted.

Additional information

  • -100,000 <= num <= 100,000
  • findMedian will only be called after at least one integer has been added.
  • At most 5 * 10^4 calls will be made to addNum and findMedian.

Example 1:

Input:
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [5], [10], [], [3], []]

Output: [null, null, null, 7.5, null, 5.0]

Explanation:

  • addNum(5) -- stream is [5]
  • addNum(10) -- stream is [5, 10]
  • findMedian() -- sorted stream is [5, 10], median is (5 + 10) / 2 = 7.5
  • addNum(3) -- stream is [3, 5, 10]
  • findMedian() -- sorted stream is [3, 5, 10], median is 5.0

Example 2:

Input:
["MedianFinder", "addNum", "findMedian"]
[[], [42], []]

Output: [null, null, 42.0]
Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →