Find Median from Data Stream

Hard Design

MedianFinder() starts with no numbers. Each call of addNum(num) adds the whole number num to the numbers it holds.

findMedian() returns the median of the numbers added so far: with the numbers in order, the middle one when there is an odd count of them, and the average of the two middle ones when the count is even.

The median is a decimal, not rounded: the median of 4 and 7 is 5.5. An answer within 10⁻⁵ of it is right.

Example 1

Calls:
MedianFinder()
addNum(6)
addNum(2)
findMedian() → 4.0
addNum(9)
findMedian() → 6.0
addNum(1)
findMedian() → 4.0

After 6 and 2 the two middle numbers are 2 and 6, so the median is 4. With 9 there are three, 2, 6 and 9, and the middle one is 6. With 1 they are 1, 2, 6 and 9, and the median is (2 + 6) / 2 = 4.

Example 2

Calls:
MedianFinder()
addNum(5)
findMedian() → 5.0
addNum(8)
findMedian() → 6.5

Example 3

Calls:
MedianFinder()
addNum(-4)
addNum(-4)
addNum(10)
findMedian() → -4.0

Constraints

  • -2³¹ ≤ num ≤ 2³¹ - 1
  • findMedian is called only after at least one addNum
  • at most 10⁵ calls in all to addNum and findMedian

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Design

All Design problems