Sign in to track progress, unlock prep layers, and browse your pipeline.Sign in
Maintain median of a data stream
Problem Description
Design a data structure that efficiently supports two operations:
addNum(int x): Adds an integerxfrom a continuous stream of data.findMedian(): Returns the median of all integers added to the data structure so far.
Median Definition
- If the total count of numbers is odd, the median is the middle element after sorting.
- If the total count of numbers is even, the median is the average of the two middle elements after sorting.
Performance Requirements
- The
addNumoperation should aim for an average time complexity ofO(log n), wherenis the number of elements currently in the data structure. - The
findMedianoperation should aim for an average time complexity ofO(1)orO(log n).
Constraints
- The total number of
addNumandfindMedianoperations can be up to approximately 10^5. - Input integers (
x) can be negative, positive, or zero, and duplicate values are allowed. - The implementation should be in C++.
AI interview prep
Core dilemma
Efficiently maintaining order statistics (specifically the median) in a dynamic data stream, balancing the cost of insertions with the speed of median queries.
Mid-level signals3
Senior signals3
Red flags3
3 tradeoffs and 2 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Maintain median of a data stream
Problem Description
Design a data structure that efficiently supports two operations:
addNum(int x): Adds an integerxfrom a continuous stream of data.findMedian(): Returns the median of all integers added to the data structure so far.
Median Definition
- If the total count of numbers is odd, the median is the middle element after sorting.
- If the total count of numbers is even, the median is the average of the two middle elements after sorting.
Performance Requirements
- The
addNumoperation should aim for an average time complexity ofO(log n), wherenis the number of elements currently in the data structure. - The
findMedianoperation should aim for an average time complexity ofO(1)orO(log n).
Constraints
- The total number of
addNumandfindMedianoperations can be up to approximately 10^5. - Input integers (
x) can be negative, positive, or zero, and duplicate values are allowed. - The implementation should be in C++.