Median of a Data Stream
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write a class MedianFinder, made with new MedianFinder(). addNum(x) adds a whole number x, and findMedian() returns the median of every number added so far: the middle one in sorted order, or the average of the two middle ones when the count is even, so it may end in .5. findMedian is only called after at least one addNum. For example, after adding 5, 1 and 3, findMedian() is 3; add 8 and it's 4. The checks make 100,000 adds, each followed by findMedian, so sorting the numbers on every call is too slow: keep the lower half in a max-heap and the upper half in a min-heap.
Your code must pass
- Finds the median of an odd count
- Averages the two middle numbers of an even count
- Handles repeats, negatives and any order
- Is fast enough for 100,000 numbers