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
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
Example 3
Constraints
-2³¹ ≤ num ≤ 2³¹ - 1findMedianis called only after at least oneaddNum- at most
10⁵calls in all toaddNumandfindMedian
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
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 roundMore Design
- LRU CacheAI round · Medium
- Min StackAI round · Medium
- Time Based Key-Value StoreAI round · Medium
- Serialize and Deserialize Binary TreeHard
- Insert Delete GetRandom O(1)Medium