Streaming Median Tracker
TrexquantSoftware Engineer · Technical ScreenLast updated
This question evaluates a candidate's ability to design a data structure that maintains a running median over a stream of numbers, testing knowledge of heaps and balanced data partitioning. It is a classic coding and algorithms interview problem used to assess understanding of amortized time complexity and efficient online statistics tracking, requiring practical implementation rather than just conceptual discussion.
Streaming Median Tracker
Design a data structure that ingests integers one at a time from a stream and can report the median of every integer inserted so far at any moment.
The median of a collection of numbers is the middle value once the numbers are arranged in non-decreasing order:
- If the collection has an odd number of elements, the median is the single middle element.
- If the collection has an even number of elements, the median is the average of the two middle elements.
Implement a class MedianTracker with the following operations:
MedianTracker()— initialize an empty tracker.add(num)— insert the integernuminto the structure. Duplicates and negative values are allowed.median()— return the median of all integers inserted so far as a floating-point number. This method is only invoked after at least one call toadd.
Example
MedianTracker t
t.add(1) // multiset = [1]
t.median() // returns 1.0
t.add(3) // multiset = [1, 3]
t.median() // returns 2.0 (average of the two middle values 1 and 3)
t.add(2) // multiset = [1, 2, 3]
t.median() // returns 2.0 (single middle value)
t.add(10) // multiset = [1, 2, 3, 10]
t.median() // returns 2.5 (average of 2 and 3)
Constraints
- Values passed to
addare 32-bit signed integers; they may be negative and may repeat. addcan be called up to $10^5$ times, interleaved arbitrarily withmediancalls. A solution that re-sorts the data on everymediancall (overall $O(n^2 \log n)$) is too slow — aim for roughly $O(\log n)$ peraddand $O(1)$ permedian.medianis never called before the firstadd.- The returned median must be exact: when the count is even, return the true average of the two middle elements (which may be a non-integer such as
2.5).
Required Output
Each call to median() returns a single floating-point number equal to the median of all integers inserted up to that point.
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.