Problem overview
The median of a list is its middle value once sorted. With an even number of values it is the mean of the two middle ones: the median of [2, 3, 4] is 3, and the median of [2, 3] is 2.5.
The class MedianFinder receives numbers one at a time. addNum(num) adds an integer, and findMedian() returns the median of everything added so far. Duplicates count each time they arrive, and asking twice in a row gives the same answer because findMedian changes nothing. It is only called after at least one number has been added, and up to 500,000 calls are made in total.
For example, after adding 1 and 2 the median is 1.5. After adding 3 the sorted numbers are [1, 2, 3] and the median is 2.
Approach: keep the two halves in two heaps
The simple approach keeps a list and sorts it whenever the median is requested. That costs O(n log n) per question, which is too slow for this many calls. Inserting each new number into a sorted list in the right place avoids the sort, but shifting elements still costs O(n) per number.
The median depends only on the middle one or two values, so the rest of the order doesn't matter. Split the numbers into a lower half and an upper half, where every value in the upper half is at least every value in the lower half. The middle values are then the largest of the lower half and the smallest of the upper half. A heap gives access to exactly those: a max-heap for the lower half, whose top is its largest value, and a min-heap for the upper half, whose top is its smallest.
The sizes are kept equal, or with the lower half one larger. Then:
- if the lower half is larger, the count is odd, and the median is the top of the lower half;
- if both halves have the same size, the median is the mean of the two tops.
Pushing and popping a heap costs O(log n), and reading its top costs O(1), which matches the lesson's budget: addNum in O(log n) and findMedian in O(1).
The heapq module only provides min-heaps, with the smallest value at index 0. To get a max-heap, store the numbers negated: the largest number becomes the smallest stored value. So self.low holds negated values, and self.high holds values as they are.
Here is the state after each addNum for the numbers 4, 3, 2, 1 (the lists are shown sorted, and low is shown with the real values, not the negated ones):
add 4 low [4] high [] median 4
add 3 low [3] high [4] median 3.5
add 2 low [2, 3] high [4] median 3
add 1 low [1, 2] high [3, 4] median 2.5
Step by step
- Create
self.lowas an empty list in__init__. It is the max-heap of the lower half, storing negated numbers. - Create
self.highas an empty list. It is the min-heap of the upper half, storing numbers as they are. - In
addNum, push-numintoself.lowwithheapq.heappush. Every new number enters the lower half first. - Move the largest value of
self.lowintoself.high. Popping the lower heap returns its smallest stored value, which is the negated largest real value. Negate it back and push it into the upper heap. Whatevernumwas, the value that leaves the lower half is its largest, so every value in the upper half stays at least every value in the lower half. - Rebalance. If
self.highnow has more values thanself.low, pop its smallest value and push it, negated, intoself.low. After this, the halves have equal sizes, orself.lowhas one more. - In
findMedian, handle the odd count. Ifself.lowhas more values, return-self.low[0]: the top, negated back. - Otherwise return the mean of the two tops:
(-self.low[0] + self.high[0]) / 2.
The solution in Python
class MedianFinder:
def __init__(self):
self.low = []
self.high = []
def addNum(self, num: int) -> None:
heapq.heappush(self.low, -num)
heapq.heappush(self.high, -heapq.heappop(self.low))
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def findMedian(self) -> float:
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
Python details worth a closer look:
- Heaps are plain lists.
heapqworks on an ordinary list and keeps the smallest element at index 0. Only that element is guaranteed in place: printing the list shows an arrangement that is not fully sorted. That is why the code readsself.low[0]and never the rest. - The negation trick. For the values -5, -9 and -1 pushed onto a heap, the top at index 0 is -9, the smallest. Storing
-numturns "smallest stored" into "largest real", and every read or pop needs a negation to get back to the real value. - Integer or float.
/always gives a float in Python 3, but the odd-count branch returns-self.low[0], which is anint. After adding only the number 7,findMedian()returns the integer7. It equals7.0in a comparison, so it is a valid median. - Methods and
self. The heaps are attributes created in__init__, so eachMedianFinderhas its own. Creating the lists at class level instead would share them between objects.
Complexity
Time: addNum is O(log n). It does at most two pushes and two pops, and each heap operation costs O(log n). findMedian is O(1): it reads one or two tops and does a bit of arithmetic.
Space: O(n). Together the two heaps hold every number added.
Edge cases and common mistakes
- One number. After
addNum(7),self.lowholds it andself.highis empty. The odd branch returns it without touchingself.high[0], which would raiseIndexErroron an empty list. - Duplicates. Adding 5, -3, -3 gives
[-3, -3, 5]and the median is -3: the repeated number counts twice. - Negative numbers. The values are negated for storage, so a negative
numis stored as a positive one. The code handles that without any special case. - Forgetting to negate on the way out. Returning
self.low[0]instead of-self.low[0]gives the sign-flipped median. - Pushing straight into one heap. Sending each number to a heap by comparing it with the tops works, but needs more cases. Sending every number through the lower half and then moving its largest value across keeps the order between the halves automatically.
- Letting the halves drift apart. If the sizes differ by more than one, or the upper half is larger, the tops are no longer the middle values. The rebalancing step prevents it.
- Sorting on every query. Calling
sortedinfindMediangives right answers but costsO(n log n)per call, which is too slow at this scale.
Testing
- Adding 1, 2, 3 and asking after each: 1, 1.5, 2.
- Adding 5, -3, -3, 10: 5, 1.0, -3, 1.0.
- Adding 4, 3, 2, 1: 4, 3.5, 3, 2.5.
- Adding only 7:
findMedian()returns 7.
