HardTwo PointersDesignSortingHeap (Priority Queue)Data Stream

Find Median from Data Stream

1 approach, code in every language

Problem description

Design a data structure that supports adding integers from a data stream and querying the median of all values received so far.

The median is the middle value of an ordered list. When the count of values is odd it is the single middle element; when the count is even it is the average of the two middle elements.

Implement the class:

- `MedianFinder()` initializes the structure. - `addNum(num)` ingests the next integer from the stream. - `findMedian()` returns the median of every value added so far as a floating-point number.

Example 1

Input: ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"] [[],[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 values are [1, 2, 3], so the median is 2.0.

Example 2

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

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

With only 5 present the median is 5.0; after adding 10 the median is (5 + 10) / 2 = 7.5.

Constraints

  • -10^5 <= num <= 10^5
  • There is at least one element before findMedian is called.
  • At most 5 * 10^4 calls are made to addNum and findMedian.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free