Solution: Find Median from Data Stream
Let's solve the Find Median from Data Stream problem using the Two 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,
Implement a struct, MedianOfStream, which should provide the following functionalities:
Init(): Initializes the data structure, setting up the necessary components to manage the stream of integers, i.e., it creates the max and the min heap.
Insert Num(num): Adds an integer,
num
, to the data structure.Find Median(): 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:
num
, 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,
calls will be made to the function that calculates the median.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.