Data Structures19 sections · 729 units
Open in Course

Median Stream - Implementation

Complete solution

Here's the solution:

class MedianFinder
    maxHeap := empty max-heap  // smaller half
    minHeap := empty min-heap  // larger half

    function addNum(num)
        insert num into maxHeap
        insert (extract max from maxHeap) into minHeap

        if size of minHeap > size of maxHeap
            insert (extract min from minHeap) into maxHeap

    function findMedian()
        if size of maxHeap > size of minHeap
            return root of maxHeap
        return (root of maxHeap + root of minHeap) / 2.0

Time: O(logn)O(\log n) per insertion, O(1)O(1) for median. Space: O(n)O(n).