Skip to content

Start typing to search patterns, problems and pages.

Heaps

People arrive one at a time and join one of two teams: the shorter half and the taller half. The shorter team only watches its tallest member, and the taller team only its shortest. The median is always where the two teams meet, so nobody ever lines everyone up by height.

⏱ about 15 minutesNeeds: arrays, treesTime O(log n)Space O(n)

2 · Watch

Heaps in 60 seconds

Numbers arrive one at a time and you must report the median after each. Re-sorting everything so far after every number does the same work over and over.

3 · Now you drive

Keys:←→ stepSpace playR resetHomeEnd jump

Find Median from Data Stream

or try
1–8 numbers from -99 to 99, in the order they arrive.
Two empty heaps: the lower half on the left, the upper half on the right.Step 1 of 16. Two empty heaps. 4 numbers arriving. No median yet.
Step 1 of 16
solution.ts
class MedianFinder {
low = new MaxHeap(); // smaller half
high = new MinHeap(); // larger half
addNum(num: number) {
this.low.push(num);
this.high.push(this.low.pop());
if (this.high.size() > this.low.size()) {
this.low.push(this.high.pop());
}
}
findMedian(): number {
if (this.low.size() > this.high.size()) return this.low.peek();
return (this.low.peek() + this.high.peek()) / 2;
}
}
▶ marks the line running now

4 · Your turn

0 of 1 problems solved

Start from this

// Min-heap: the smallest kept item is on top.
const heap = new MinHeap<number>();
for (const x of nums) {
  heap.push(x);
  // Too many: drop the smallest, keep the k largest.
  if (heap.size() > k) heap.pop();
}
// The top is now the kth largest.
return heap.peek();

Easy ways to go wrong

  • Using a max-heap for “k largest”. A min-heap of size k is cheaper.
  • Forgetting that Python’s heapq is a min-heap. Negate values for a max-heap.
  • Sorting everything when you only need the top k.
  1. Hard01

    Find Median from Data Stream

    LeetCode 295 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

UP NEXT · LESSON 12 OF 20BacktrackingTry, recurse, undo.