File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments