Track the Median of a Stream
Hive.AiSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to maintain sorted order in a streaming context using balanced data structures to achieve optimal time complexity for insertions and median retrieval.
Problem Statement
Design a data structure MedianTracker that accepts a stream of integers and provides the current median at any point in time.
Implement the following methods:
add_num(num: int) -> None: Adds an integer from the stream to the data structure.find_median() -> float: Returns the median of all elements added so far. If the number of elements is even, return the average of the two middle elements.
Constraints
-10^6 <= num <= 10^6add_numandfind_medianmust be called at most 5 * 10^4 times each.- The time complexity for
add_numshould beO(log n)andfind_medianshould beO(1).
Examples
# Example 1
tracker = MedianTracker()
tracker.add_num(1)
tracker.add_num(2)
tracker.find_median() # Returns 1.5 ( (1+2)/2 )
tracker.add_num(3)
tracker.find_median() # Returns 2.0
Edge Cases
- Stream is empty when
find_medianis called (return 0 or handle as needed). - Stream contains negative numbers.
- Stream contains duplicate numbers.
Implementation Template
class MedianTracker:
def __init__(self):
pass
def add_num(self, num: int) -> None:
pass
def find_median(self) -> float:
pass
Hints
Hint 1
Maintain two balanced heaps: a max-heap to store the smaller half of the numbers and a min-heap to store the larger half.
Hint 2
Ensure the max-heap size is either equal to or exactly one greater than the min-heap size to keep the median easily accessible.
Hint 3
When adding a number, push it into one heap, then re-balance the two heaps to maintain the size invariant.
Follow-up questions
- How would you modify your design if you needed to support a `remove_num(num)` operation in O(log n) time?
- What changes are required if the stream consists of floating-point numbers instead of integers?
- How would you handle the memory constraints if the stream contained billions of elements and could not fit into RAM?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.