How does the find median from a data stream problem use two heaps?
LeetCode Patterns Flashcards: Heap and Priority Queue, Top K, Merge K Sorted
Аудио-карточка · 0:30Nortren·
How does the find median from a data stream problem use two heaps?
0:30
Maintain two heaps: a max-heap for the lower half and a min-heap for the upper half. Keep their sizes balanced so they differ by at most one element. When a new number arrives, add it to the max-heap if it is less than or equal to the max-heap top, otherwise add it to the min-heap. Then rebalance if sizes differ by more than one by moving the top of the larger heap to the smaller. The median is the top of the larger heap if sizes differ, or the average of both tops if sizes are equal. Each insertion takes O of log n time. This maintains a running median efficiently.
neetcode.io