Design a data structure that supports adding numbers one by one and querying the current median at any time.
Design a class-like data structure that processes integers from a stream.
You must support two operations:
addNum(num): insert an integer into the data structurefindMedian(): return the median of all inserted numbers so farThe median is:
Your implementation should handle many insertions efficiently and answer median queries quickly.
addNum operation provides one integer.findMedian operation asks for the median of all numbers inserted so far.findMedian query, return the current median as a number.findMedian() is called only after at least one number has been inserted.Example 1
Input
addNum(1) addNum(2) findMedian() addNum(3) findMedian()
Output
1.5 2
Explanation
After inserting 1 and 2, the median is (1 + 2) / 2 = 1.5. After adding 3, the sorted stream is [1, 2, 3], so the median is 2.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.