Insert 5 Insert 15 Insert 1 Insert 3 Find median
After inserting 5, median is 5.
After 15, median is (5+15)/2 = 10.
After 1, median is 5.
After 3, median is (3+5)/2 = 4.
The two heaps split the data into smaller and larger halves. The max heap stores the smaller half so its root is the largest of the smaller numbers. The min heap stores the larger half so its root is the smallest of the larger numbers. This allows quick median calculation.
if (maxHeap.size() === 0 || num > maxHeap.peek()) { minHeap.insert(num); } else { maxHeap.insert(num); } if (maxHeap.size() - minHeap.size() > 1) { minHeap.insert(maxHeap.extract()); } else if (minHeap.size() - maxHeap.size() > 1) { maxHeap.insert(minHeap.extract()); }
If maxHeap is empty, calling peek() returns undefined or throws an error. Comparing num > undefined causes a runtime error.
Insert 10 Insert 20 Insert 30 Insert 40 Insert 50 Find median
After inserting all numbers, the median is the middle number 30.
Insertion into a heap takes O(log n) time. Median retrieval is O(1) because it is the root of one or both heaps.
