Problem overview
The median of a list of numbers is the middle value once the list is sorted. With an even number of values there is no single middle, and the median is the mean of the two middle values: 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 and answers questions in between. addNum(_ num: Int) adds an integer, and findMedian() -> Double returns the median of everything added so far. findMedian is only called after at least one addNum, and it changes nothing, so asking twice gives the same answer.
Example: after addNum(1) and addNum(2), the median is 1.5. After addNum(3) the numbers are [1, 2, 3] and the median is 2.0. A number that arrives twice counts twice: after 5, -3 and -3 the sorted numbers are [-3, -3, 5] and the median is -3.0.
The statement asks for addNum in O(log n) time and findMedian in O(1) time.
Approach: two heaps around the middle
The simplest approach keeps all numbers in an array and sorts it for each question, which costs O(n log n) per call to findMedian. Inserting each number into its place in a sorted array is O(n) because the later elements shift. Neither meets the budget.
The median depends only on the middle one or two values, so the data structure only needs quick access to those. Split the sorted numbers into two halves:
low, a max-heap, holds the smaller half. Its top is the largest value of that half.high, a min-heap, holds the larger half. Its top is the smallest value of that half.
The two middle values are then exactly the two tops. A heap gives its top in O(1) and inserts or removes in O(log n), which matches the budget.
The halves must obey two rules after every addNum: every value in high is at least every value in low, and the sizes are equal or low has exactly one more. With these rules, an odd count has its median at the top of low, and an even count has it between the two tops.
Keeping the rules takes three moves. Insert the new number into low. Then move the largest value of low into high. Whatever the new number was, the value that leaves low is its largest, so everything in high stays at least everything in low. Finally, if high now holds more values than low, move its smallest value back. Each move is one heap insert and one extract, so adding a number costs O(log n).
Here is the state after each call on the numbers 5, -3, -3, 10, 7, 1:
added median low size high size low top high top
5 5.0 1 0 5 -
-3 1.0 1 1 -3 5
-3 -3.0 2 1 -3 5
10 1.0 2 2 -3 5
7 5.0 3 2 5 7
1 3.0 3 3 1 5
Step by step
- Declare
lowasvar low = MaxHeap(), the lower half. The lesson provides ready-to-useMaxHeapandMinHeapstructs withinsert(_:),extract(),peek(),countandisEmpty. They are structs whose methods change them, so the properties must bevar. - Declare
highasvar high = MinHeap(), the upper half. - In
addNum, insertnumintolow. Every new number goes into the lower half first, and the next lines restore the order. - Move the largest value of
lowintohighin one line:extract()removes and returns the top oflow, andinsertputs it intohigh. - Rebalance. If
high.count > low.count, move the smallest value ofhighback intolow. This keeps the sizes equal, orlowone larger. - In
findMedian, handle the odd case. Iflowholds more values thanhigh, its top is the middle value, so returnDouble(low.peek()). Swift never converts anIntto aDoubleon its own. - Handle the even case. Both halves have the same size, so return the sum of the two tops, converted to
Double, divided by 2.
The solution in Swift
class MedianFinder {
var low = MaxHeap()
var high = MinHeap()
func addNum(_ num: Int) {
low.insert(num)
high.insert(low.extract())
if high.count > low.count {
low.insert(high.extract())
}
}
func findMedian() -> Double {
if low.count > high.count {
return Double(low.peek())
}
return Double(low.peek() + high.peek()) / 2
}
}
The Swift details worth a closer look:
varfor the heaps. The heaps are value types (structs), andinsertandextractaremutatingmethods. Withlet low = MaxHeap(), the calllow.insert(n)fails to compile withcannot use mutating member on immutable value: 'low' is a 'let' constant.MedianFinderis a class, so its methods can change itsvarproperties without being markedmutating.- No automatic conversion to
Double. Returning anIntfrom a function declared to returnDoubleis a compile error:cannot convert return expression of type 'Int' to return type 'Double'. That is why both returns useDouble(...). - Convert before dividing.
Double(low.peek() + high.peek()) / 2divides aDoubleby 2, which gives 2.5 for a sum of 5. WritingDouble((low.peek() + high.peek()) / 2)divides theIntsum first, and integer division in Swift truncates toward zero:Double(7 / 2)is 3.0, whileDouble(7) / 2is 3.5. - The literal
2adapts. InDouble(...) / 2, the literal2is read as aDouble, so no conversion is needed for it. - Method calls in arguments.
high.insert(low.extract())first runslow.extract(), which changeslowand returns its top, and then inserts that value intohigh. The two calls touch different properties, so there is no conflict.
Complexity
addNum: O(log n). It performs at most two inserts and two extracts on heaps of at most n values, and each one is O(log n).
findMedian: O(1). It reads the top of one or both heaps and does one addition and one division.
Space: O(n). Every number added is stored in exactly one of the two heaps.
Edge cases and common mistakes
- A single number. After
addNum(5), the number moves tohighand back tolow, solowholds it andhighis empty.findMedianreturns 5.0 without touchinghigh, which is why the odd case must come first. Callinghigh.peek()on an empty heap would be an error. - Duplicates. After 5, -3 and -3 the median is -3.0. Both heaps keep every copy.
- Even counts. After 2 and 3 the median is 2.5, and after 4, 3, 2 and 1 it is 2.5 as well.
- Not sorted input. Numbers can arrive in any order. The three-move routine handles each one the same way, whether it is a new smallest, a new largest or in between.
- Asking twice.
findMedianonly reads the heaps, so repeating the call gives the same value. After 4 and 3, two calls both give 3.5. - Letting
highgrow larger thanlow. The odd case readslow.peek(), which is only right iflowis the larger half. The rebalancingifguarantees it. - Integer division. Dividing the integer sum by 2 before converting loses the half.
Testing
addNum(1),addNum(2),findMedian()gives 1.5. AfteraddNum(3),findMedian()gives 2.0.addNum(5),findMedian()gives 5.0. ThenaddNum(-3)gives 1.0, a secondaddNum(-3)gives -3.0, andaddNum(10)gives 1.0.addNum(4),addNum(3), then twofindMedian()calls give 3.5 and 3.5. AfteraddNum(2)andaddNum(1)it gives 2.5.- Adding 100000 twice gives 100000.0.
