Design a data structure to efficiently calculate the running median of a continuously growing stream of numbers. This tests knowledge of heaps and data structure design under dynamic constraints, a common interview theme.
Implement a MedianFinder class that supports the following operations: - add_number(num: int): Adds a new integer num to the data structure. - find_median() -> float: Returns the median of all numbers added so far. If the number of elements is even, return the average of the two middle elements.
The brute force approach involves storing all numbers in a list and, upon each find_median call, sorting the list and returning the median. Imagine you're a librarian who has to find the middle book on a shelf every time a new book is added - you'd have to re-sort the entire shelf each time. This is inefficient because sorting takes a long time. The time complexity is dominated by sorting.
Work through this problem with AI coaching and get real-time feedback
Practice This Problem