LC 295: Find Median from Data Stream
Solved using two heaps to maintain a running median.:: ON THIS PAGE 3
The Idea
We need to find the median of a growing stream of numbers efficiently. Sorting every time would be $O(n \log n)$ per insert — way too slow.
The trick: split the numbers into two halves using two heaps.
- Max-heap (
lo): stores the smaller half. The top is the largest of the small numbers. - Min-heap (
hi): stores the larger half. The top is the smallest of the large numbers.
If both heaps are the same size, the median is the average of both tops. If one heap has one extra element, that top is the median.
Stream: [2, 3, 1, 5, 4]
After 2: lo=[2] hi=[] → median = 2
After 3: lo=[2] hi=[3] → median = (2+3)/2 = 2.5
After 1: lo=[1,2] hi=[3] → median = 2
After 5: lo=[1,2] hi=[3,5] → median = (2+3)/2 = 2.5
After 4: lo=[1,2,3] hi=[4,5] → median = 3
Implementation
= # max-heap (negate values since Python only has min-heap)
= # min-heap
# Always add to max-heap first
# Ensure max of lo <= min of hi
= -
# Balance sizes: lo can have at most 1 more element than hi
= -
=
return -
return / 2.0
Complexity
- addNum: $O(\log n)$ — heap push/pop operations
- findMedian: $O(1)$ — just peek at the tops
- Space: $O(n)$ — storing all elements across both heaps
> finding connected notes…
> 4 notes share a tag
207-course-schedule.md LC 207: Course Schedule 210-course-schedule-2.md LC 210: Course Schedule II 443-string-compression.md LC 443: String Compression 01-two-sum.md LC 001: Two Sum