Skip to content

Commit 8d3a5b0

Browse files
committed
solve: findMedianFromDataStream
1 parent 77f1223 commit 8d3a5b0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time Complexity:
2+
# - addNum(): O(log N) - use a heap operation (push/pop) which takes log N time.
3+
# - findMedian(): O(1) - just accessing the top elements of heaps.
4+
# Space Complexity: O(N) - store all elements in two heaps.
5+
6+
7+
class MedianFinder:
8+
def __init__(self):
9+
# max heap (stores the smaller half of numbers, negated values for max heap behavior)
10+
self.maxHeap = []
11+
# min heap (stores the larger half of numbers)
12+
self.minHeap = []
13+
14+
def addNum(self, num: int) -> None:
15+
if not self.maxHeap or num <= -self.maxHeap[0]:
16+
# store as negative to simulate max heap
17+
heapq.heappush(self.maxHeap, -num)
18+
else:
19+
heapq.heappush(self.minHeap, num)
20+
21+
# balance the heaps: maxHeap can have at most 1 more element than minHeap
22+
if len(self.maxHeap) > len(self.minHeap) + 1:
23+
heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap))
24+
elif len(self.minHeap) > len(self.maxHeap):
25+
heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap))
26+
27+
def findMedian(self) -> float:
28+
if len(self.maxHeap) > len(self.minHeap):
29+
return -self.maxHeap[0] # odd number of elements, maxHeap has the median
30+
else:
31+
return (-self.maxHeap[0] + self.minHeap[0]) / 2.0 # even case, average of two middle numbers

0 commit comments

Comments
 (0)