The median is the middle value in an ordered integer list. If the list size is even, the median is the mean of the two middle values.
Implement MedianFinder:
addNum(int num) adds an integer from the data stream,
findMedian() returns the median of all elements so far.
addNum(1), addNum(2), findMedian(), addNum(3), findMedian()[1.5, 2.0]addNum(6), addNum(3), findMedian(), addNum(7), addNum(2), findMedian()[4.5, 4.5]maxH = max-heap (lower half), minH = min-heap (upper half)num to maxH, then push maxH.poll() to minHminH.size > maxH.size, move minH.poll() to maxHfindMedian: if maxH.size > minH.size → maxH.peek(); else → avg of topsWe keep the stream split at the median boundary: maxH (max-heap) holds the lower half so its top is the largest small value, and minH (min-heap) holds the upper half so its top is the smallest large value. By ensuring sizes stay balanced (equal or maxH one larger), the median is always instantly available at the heap tops — no scanning needed. Each addNum is O(log n), findMedian is O(1).
Keeping a sorted list makes each insertion O(n). Sorting again for every query is even slower. Two heaps give O(log n) insertion and O(1) median.
Split the numbers into a lower half and an upper half. The lower half lives in a max heap, so its largest value is on top. The upper half lives in a min heap, so its smallest value is on top. Keep the sizes balanced, with the lower half allowed one extra number. Then the median is the top of the lower heap, or the average of both tops.
A max heap for the lower half, and a min heap for the upper half. Their tops meet in the middle.
Run the animation above on your own input, or watch the 1:60 video explanation of Find Median from Data Stream with a dry run and Java code.