|
| 1 | +import heapq |
| 2 | + |
| 3 | +class KthLargest: |
| 4 | + # Constructor to initialize heap and add values in it |
| 5 | + def __init__(self, k, nums): |
| 6 | + |
| 7 | + self.top_k_heap = [] |
| 8 | + self.k = k |
| 9 | + |
| 10 | + for element in nums: |
| 11 | + self.add(element) |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | + # Adds element in the heap and return the Kth largest |
| 16 | + def add(self, val): |
| 17 | + |
| 18 | + if len(self.top_k_heap) < self.k: |
| 19 | + heapq.heappush(self.top_k_heap, val) |
| 20 | + |
| 21 | + elif val > self.top_k_heap[0]: |
| 22 | + heapq.heappop(self.top_k_heap) |
| 23 | + heapq.heappush(self.top_k_heap, val) |
| 24 | + |
| 25 | + return self.top_k_heap[0] |
| 26 | + |
| 27 | + |
| 28 | +# Time Complexity = O(logk) |
| 29 | +# Space Complexity = O(K) |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +############################################################################ |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | +# Driver code |
| 38 | +def main(): |
| 39 | + nums = [3, 6, 9, 10] |
| 40 | + temp = [3, 6, 9, 10] |
| 41 | + print("Initial stream: ", nums, sep = "") |
| 42 | + print("k: ", 3, sep = "") |
| 43 | + k_largest = KthLargest(3, nums) |
| 44 | + val = [4, 7, 10, 8, 15] |
| 45 | + for i in range(len(val)): |
| 46 | + print("\tAdding a new number ", val[i], " to the stream", sep = "") |
| 47 | + temp.append(val[i]) |
| 48 | + print("\tNumber stream: ", temp, sep = "") |
| 49 | + print("\tKth largest element in the stream: ", k_largest.add(val[i])) |
| 50 | + print("-"*100) |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + main() |
| 54 | + |
| 55 | + |
0 commit comments