...

/

Solution: Find Median from Data Stream

Solution: Find Median from Data Stream

Let's solve the Find Median from Data Stream problem using the Heaps pattern.

Statement

Create a data structure that can store a list of integers that can change in size over time and find the median from this dynamically growing list in constant time, O(1)O(1).

Implement a class, MedianOfStream, which should support the following operations:

  1. Constructor(): This initializes the object of this class, which in turn creates the max and the min heap.

  2. Insert Num(num): This adds an integer, num, to the data structure.

  3. Find Median(): This finds the median of all elements seen so far. If there are an even number of elements, return the average of the two middle values.

Constraints:

  • 105-10^5 \leq num 105\leq 10^5, where num is an integer received from the data stream.

  • There will be at least one element in the data structure before the median is computed.

  • At most, 500500 calls will be made to the function that calculates the median.

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of ...

Access this course and 1400+ top-rated courses and projects.