Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
Build a class MedianFinder with:
MedianFinder(): start with no numbers;addNum(num): add the integernumto the collection;findMedian(): return the median of all numbers added so far, as a decimal.
The median is the middle value in sorted order. With an even count, it's the average of the two middle values. findMedian is only called after at least one add. Up to 5 × 10⁴ calls in total, and values run from −10⁵ to 10⁵.
Example:
addNum(1) collection [1]
addNum(2) collection [1, 2]
findMedian() → 1.5
addNum(3) collection [1, 2, 3]
findMedian() → 2.0Start with brute force
Option A: keep a plain list. addNum appends in O(1). findMedian sorts in O(n log n) and reads the middle. With 5 × 10⁴ calls split evenly, that's about 2.5 × 10⁴ sorts of up to 2.5 × 10⁴ items, roughly 10¹⁰ steps.
Option B: keep the list sorted. Insert with binary search plus a shift, which is O(n) per add because of the shift. Then findMedian is O(1). With 5 × 10⁴ adds, that's over 6 × 10⁸ element moves in the worst case. Better, but still too slow, and it's not what the interviewer is looking for.
Building the intuition
This Hard is two Medium ideas stacked together: "a heap gives you the top of a group in O(1)" (Kth Largest Element in a Stream) and "split the problem at the median" (the same picture as Median of Two Sorted Arrays).
Step 1: what does the median actually need? Sort the numbers and draw a line down the middle:
smaller half | larger half
1 3 4 [5] | [7] 8 9 12The median is (5 + 7) / 2. You never looked at 1, 3, 4, 8, 9 or 12. You only need the largest of the smaller half and the smallest of the larger half. The rest just needs to be on the correct side.
Step 2: "largest of a changing group" is a max-heap. Keep the smaller half in a max-heap (low), whose top is its largest. Keep the larger half in a min-heap (high), whose top is its smallest. The two tops sit right next to the line.
Step 3: two rules to maintain.
- Order: every number in
lowis ≤ every number inhigh. - Balance:
lowhas the same size ashigh, or exactly one more.
With both rules holding: if low is bigger, the count is odd and the median is low's top. Otherwise it's the average of the two tops.
Step 4: adding without breaking the rules. A new number might belong on either side. A neat trick avoids case analysis:
- push
numintolow; - pop
low's top (the largest oflowplusnum) and push it intohigh. Now order holds, because whatever moved was ≥ everything left inlow; - if
highis now bigger thanlow, pophigh's top and push it intolow. Balance holds again, and order still holds, becausehigh's smallest is moving down.
That's at most three heap operations per add.
The optimal approach
low= max-heap,high= min-heap, both empty.addNum(num): push intolow, movelow's top tohigh, and iflen(high) > len(low), movehigh's top back tolow.findMedian(): iflen(low) > len(high), returnlow's top. Otherwise return(low.top + high.top) / 2.
The subtle detail: getting a max-heap in each language. Python's heapq is only a min-heap, so low stores negated values: push -num, and read -low[0]. C++'s priority_queue<int> is already a max-heap, and the min-heap is priority_queue<int, vector<int>, greater<int>>. Java uses PriorityQueue with Collections.reverseOrder(). JavaScript has no heap at all, so the solution includes a small MinHeap class that takes a comparison function. Passing (a, b) => a > b turns it into a max-heap.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
import heapq
class MedianFinder:
def __init__(self):
# low holds the smaller half as a max-heap (heapq is a min-heap, so we
# store negatives). high holds the larger half as a min-heap.
# Invariant: len(low) == len(high) or len(low) == len(high) + 1.
self.low = []
self.high = []
def addNum(self, num: int) -> None:
# Push through low first, so the largest of the small half moves up to
# high. That keeps every element of low <= every element of high.
heapq.heappush(self.low, -num)
heapq.heappush(self.high, -heapq.heappop(self.low))
# Rebalance: low may be bigger by one, never smaller.
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): # odd count: the middle is low's top
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2class MedianFinder {
public:
MedianFinder() {}
void addNum(int num) {
// Push through low first, so the largest of the small half moves up to
// high. That keeps every element of low <= every element of high.
low.push(num);
high.push(low.top());
low.pop();
// Rebalance: low may be bigger by one, never smaller.
if (high.size() > low.size()) {
low.push(high.top());
high.pop();
}
}
double findMedian() {
if (low.size() > high.size()) return low.top(); // odd count: the middle is low's top
return ((double)low.top() + high.top()) / 2.0; // cast first: the sum can overflow int
}
private:
// low = smaller half (max-heap), high = larger half (min-heap).
// Invariant: low.size() == high.size() or low.size() == high.size() + 1.
priority_queue<int> low;
priority_queue<int, vector<int>, greater<int>> high;
};class MedianFinder {
// low = smaller half (max-heap), high = larger half (min-heap).
// Invariant: low.size() == high.size() or low.size() == high.size() + 1.
private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());
private final PriorityQueue<Integer> high = new PriorityQueue<>();
public MedianFinder() {}
public void addNum(int num) {
// Push through low first, so the largest of the small half moves up to
// high. That keeps every element of low <= every element of high.
low.offer(num);
high.offer(low.poll());
// Rebalance: low may be bigger by one, never smaller.
if (high.size() > low.size()) low.offer(high.poll());
}
public double findMedian() {
if (low.size() > high.size()) return low.peek(); // odd count: the middle is low's top
return ((double) low.peek() + high.peek()) / 2.0; // cast first: the sum can overflow int
}
}// JavaScript has no built-in heap, so here is a small binary heap.
// less(a, b) says whether a should come out before b.
class MinHeap {
constructor(less) {
this.less = less;
this.items = [];
}
size() {
return this.items.length;
}
peek() {
return this.items[0];
}
push(x) {
const a = this.items;
a.push(x);
let i = a.length - 1;
while (i > 0) { // sift up: swap with the parent while we beat it
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.items;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) { // sift down: swap with the better child while it beats us
const l = 2 * i + 1, r = l + 1;
let best = i;
if (l < a.length && this.less(a[l], a[best])) best = l;
if (r < a.length && this.less(a[r], a[best])) best = r;
if (best === i) break;
[a[i], a[best]] = [a[best], a[i]];
i = best;
}
}
return top;
}
}
class MedianFinder {
constructor() {
// low = smaller half; reversing the comparison makes it a max-heap.
// high = larger half, a normal min-heap.
// Invariant: low.size() === high.size() or low.size() === high.size() + 1.
this.low = new MinHeap((a, b) => a > b);
this.high = new MinHeap((a, b) => a < b);
}
/**
* @param {number} num
* @return {void}
*/
addNum(num) {
// Push through low first, so the largest of the small half moves up to
// high. That keeps every element of low <= every element of high.
this.low.push(num);
this.high.push(this.low.pop());
// Rebalance: low may be bigger by one, never smaller.
if (this.high.size() > this.low.size()) this.low.push(this.high.pop());
}
/**
* @return {number}
*/
findMedian() {
if (this.low.size() > this.high.size()) return this.low.peek(); // odd count: low's top
return (this.low.peek() + this.high.peek()) / 2;
}
}Dry run
Add 5, 2, 8, 1, asking for the median after each.
| Add | After push into low | After moving low's top to high | Rebalance? | low | high | Median |
|---|---|---|---|---|---|---|
| 5 | low {5} | low {}, high {5} | high bigger → move 5 back | {5} | {} | 5 |
| 2 | low {5, 2} | low {2}, high {5} | sizes equal | {2} | {5} | (2 + 5) / 2 = 3.5 |
| 8 | low {8, 2} | low {2}, high {5, 8} | high bigger → move 5 | {5, 2} | {8} | 5 |
| 1 | low {5, 2, 1} | low {2, 1}, high {5, 8} | sizes equal | {2, 1} | {5, 8} | (2 + 5) / 2 = 3.5 |
Check the last row: sorted [1, 2, 5, 8], so the median is (2 + 5) / 2 = 3.5. Correct.
Complexity
- Time: O(log n) per
addNum. At most three heap pushes or pops. O(1) perfindMedian: just two peeks. - Space: O(n). Every number is stored in exactly one heap.
Edge cases and traps
- Integer division.
(2 + 5) / 2must be3.5. In Java and C++, cast todoublebefore adding. That also avoidsintoverflow in other versions with large values. - Forgetting the order rule. Pushing straight into whichever heap is smaller keeps the sizes balanced but can put a big number in
low. Always pass throughlowand thenhigh, or compare with the tops first. - Python sign errors.
lowholds negatives. Push-num, and read-low[0]. Mixing these up is the most common bug. - Balance the other way round. If you let
highbe the bigger one instead, the odd-count median ishigh's top. Either convention works. Just pick one and keepfindMedianconsistent with it. - Duplicates.
5, 5, 5works fine. Ties can sit on either side of the line.
Say it in the interview
"The median only depends on the two numbers next to the middle. So I keep the smaller half in a max-heap and the larger half in a min-heap, with the small side allowed to hold one extra. To add, I push into the small heap, move its top to the large heap so the order stays right, and move one back if the large heap gets bigger. The median is either the small heap's top or the average of both tops. That's O(log n) per add, O(1) per query, and O(n) space."
Follow-ups interviewers ask
- "All numbers are between 0 and 100." Keep 101 counters.
addNumis O(1).findMedianwalks the counters to the middle, O(101), which is constant. - "99% of numbers are in 0–100." Counters for the common range, plus two small sorted lists (or heaps) for the outliers below and above. The median almost always lands in the counter range.
- "Median of a sliding window of the last k numbers." (LeetCode 480.) The same two heaps, but you also need to remove the number leaving the window. Use lazy deletion (a hash map of numbers to delete when they reach a top), or use two balanced sorted multisets instead of heaps.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free