Introduction
Median Finder is a data structure that:
- continuously receives numbers
- efficiently returns the median
- supports real-time updates
Goal:
- insert numbers quickly
- find median efficiently
Example:
addNum(1)Median = 1
addNum(2)
Median = 1.5
addNum(3) Median = 2
Explanation:
Sorted Numbers:
[1]
[1,2][1,2,3]
This problem is one of the most important applications of:
Two Heaps Constraints
-10^5 <= Number <= 10^5At most 5 * 10^4 operationsApproach : Two Heaps
Explanation
The idea is:
- Max Heap stores smaller half
- Min Heap stores larger half
Rules:
Max Heap contains smaller valuesMin Heap contains larger valuesSize difference must not exceed 1
Steps:
- Insert number.
- Place into correct heap.
- Balance heaps.
- Calculate median.
Observation:
Middle values always remain at the top of heaps. This approach:
- supports streaming data
- provides efficient median lookup
Dry Run
Insert 1Max Heap:
[1]
Median = 1
----------------
Insert 2
Max Heap:
[1]
Min Heap:
[2]
Median: (1 + 2) / 2 = 1.5
----------------
Insert 3 Max Heap:
[1]
Min Heap:
[2,3]
Median = 2
Practice