Skip to content
HardHeapAI interview only

Find Median from Data Stream

Asked atamazongooglemetamicrosoftapplebloombergnetflixgoldman-sachs

01 · 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 example, 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^-5 of the actual answer will be accepted.

02 · Examples

Example 01
Input
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
arguments = [[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

After adding 1 and 2, the median is (1+2)/2 = 1.5. After adding 3, the sorted list is [1,2,3] and the median is 2.0.

Example 02
Input
operations = ["MedianFinder", "addNum", "findMedian"]
arguments = [[], [5], []]
Output
[null, null, 5.0]

With only one element, the median is that element itself: 5.0.

Example 03
Input
operations = ["MedianFinder", "addNum", "addNum", "addNum", "addNum", "findMedian"]
arguments = [[], [1], [2], [3], [4], []]
Output
[null, null, null, null, null, 2.5]

The sorted list is [1,2,3,4]. With an even count, the median is (2+3)/2 = 2.5.

03 · Constraints

  • 01-105 <= num <= 105
  • 02There will be at least one element in the data structure before calling findMedian
  • 03At most 5 * 104 calls will be made to addNum and findMedian

04 · Optimal complexity

Time
O(log n) per addNum, O(1) per findMedian
Space
O(n)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.