Problem
Section titled “Problem”The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
- For example, for
arr = [2,3,4], the median is3. - For example, for
arr = [2,3], the median is(2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder()initializes theMedianFinderobject.void addNum(int num)adds the integernumfrom the data stream to the data structure.double findMedian()returns the median of all elements so far. Answers within of the actual answer will be accepted.
Example 1:
Input["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"][[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]
ExplanationMedianFinder medianFinder = new MedianFinder();medianFinder.addNum(1); // arr = [1]medianFinder.addNum(2); // arr = [1, 2]medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)medianFinder.addNum(3); // arr[1, 2, 3]medianFinder.findMedian(); // return 2.0Constraints:
-
num - There will be at least one element in the data structure before calling
findMedian. - At most calls will be made to
addNumandfindMedian.
Follow-up:
- If all integer numbers from the stream are in the range
[0, 100], how would you optimize your solution? - If
99%of all integer numbers from the stream are in the range[0, 100], how would you optimize your solution?
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”The median depends only on the one or two values in the middle of the sorted data. Keeping everything sorted costs per insertion, but we never need full order — only the boundary between the lower and the upper half.
So split the numbers into two halves:
lo, a max-heap holding the smaller half, solo.top()is the largest of the small numbers;hi, a min-heap holding the larger half, sohi.top()is the smallest of the large numbers.
Maintain two invariants: every value in lo is <= every value in hi, and lo has either the same number of elements as hi or exactly one more. Then the median is lo.top() when the total is odd, and the mean of lo.top() and hi.top() when it is even.
Algorithm
Section titled “Algorithm”addNum(num):- Push
numintolo, then movelo’s largest element tohi. Whatevernumwas, the element that ends up inhiis at least as large as everything left inlo, so the ordering invariant holds. - If
hinow has more elements thanlo, movehi’s smallest element back tolo, which restores the size invariant.
- Push
findMedian(): iflois larger, returnlo.top(); otherwise return(lo.top() + hi.top()) / 2.0.
Walkthrough
Section titled “Walkthrough”The stream 5, 15, 1, 3, 8, 7, drawn as the sorted list of numbers seen so far. Blue cells are in lo, orange cells in hi; the heap tops are the two cells at the boundary:
Complexity
Section titled “Complexity”- Time: per
addNum(at most three heap pushes/pops) and perfindMedian. - Space: — every number is stored in exactly one heap.
Edge cases
Section titled “Edge cases”- One element: it ends up in
lo(pushed tolo, moved tohi, moved back), sofindMedianreturns it. - Duplicates and negative numbers: the comparisons are plain
<=/>=onint, so they need no special care;lo.top() + hi.top()is at most in absolute value, so the sum cannot overflow.
Follow-up
Section titled “Follow-up”- All numbers in
[0, 100]: keep a count arraycnt[101]and the totaln.addNumis ;findMedianwalks the 101 buckets to find the element(s) at rank(n - 1) / 2andn / 2— constant time. - 99% in
[0, 100]: keep the 101 buckets plus two counters (or small sorted containers) for values below0and above100. The median is almost certainly inside the bucket range; when its rank falls among the outliers, look it up in the corresponding container, which holds only about 1% of the data.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class MedianFinder { priority_queue<int> lo; // smaller half, max at top priority_queue<int, vector<int>, greater<int>> hi; // larger half, min at top
public: MedianFinder() {}
void addNum(int num) { lo.push(num); hi.push(lo.top()); lo.pop(); if (hi.size() > lo.size()) { lo.push(hi.top()); hi.pop(); } }
double findMedian() { if (lo.size() > hi.size()) return lo.top(); return (lo.top() + hi.top()) / 2.0; }};class MedianFinder { private final PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder()); // smaller half, max at top private final PriorityQueue<Integer> hi = new PriorityQueue<>(); // larger half, min at top
public MedianFinder() {}
public void addNum(int num) { lo.offer(num); hi.offer(lo.poll()); if (hi.size() > lo.size()) lo.offer(hi.poll()); }
public double findMedian() { if (lo.size() > hi.size()) return lo.peek(); return (lo.peek() + hi.peek()) / 2.0; }}import heapq
class MedianFinder:
def __init__(self): self.lo = [] # smaller half as negatives, so -lo[0] is its max self.hi = [] # larger half, min at hi[0]
def addNum(self, num: int) -> None: heapq.heappush(self.hi, -heapq.heappushpop(self.lo, -num)) if len(self.hi) > len(self.lo): heapq.heappush(self.lo, -heapq.heappop(self.hi))
def findMedian(self) -> float: if len(self.lo) > len(self.hi): return float(-self.lo[0]) return (-self.lo[0] + self.hi[0]) / 2.0Give it a try first
Attempt the problem on LeetCode — the code will still be here.





