The Two Heaps pattern is used for:
This pattern is frequently used in sliding window, online median, and kth element problems.
The idea is to split the data into two parts:
This way, the median (or approximate middle) can be found efficiently.
Compare to sorted array adding elements, maintaining sorted property takes O(n) shifting, but two heap takes O(log n) time.
func findMedian() float64 {
if maxHeap.Len() == minHeap.Len() {
return float64(maxHeap.Top()+minHeap.Top()) / 2
}
if maxHeap.Len() < minHeap.Len() {
return float64(minHeap.Top())
}
return float64(maxHeap.Top())
}
func addNum(num int) {
if maxHeap.Len() == 0 || num <= maxHeap.Top() {
heap.Push(maxHeap, num)
} else {
heap.Push(minHeap, num)
}
// Rebalance
if maxHeap.Len() > minHeap.Len()+1 {
heap.Push(minHeap, heap.Pop(maxHeap))
} else if maxHeap.Len()+1 < minHeap.Len() {
heap.Push(maxHeap, heap.Pop(minHeap))
}
}
https://leetcode.com/problems/find-median-from-data-stream
Last review: Sep 13, 2025 Next review: You understood the broad concept, but you struggled with details.
Similar Questions: