Maintain median of a data stream
TrexquantSoftware Engineer · OnsiteLast updated
This question evaluates proficiency in streaming data aggregation, dynamic order-statistics maintenance, and algorithmic complexity analysis for insertion and query operations.
Design a data structure that supports:
addNum(int x): Add an integer from a stream.findMedian(): Return the median of all inserted numbers so far.
Median definition:
- If the count is odd: the middle element after sorting.
- If the count is even: average of the two middle elements.
Requirements
- Aim for
O(log n)per insertion andO(1)(orO(log n)) per median query. - Implement in C++.
Constraints
- Up to ~10^5 insertions/queries.
- Values may be negative and can repeat.
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.