703. Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
from heapq import heapify, heappop, heappush 
class KthLargest: 
    def __init__(self, k: int, nums: List[int]): 
        self.h = nums[:k] 
        self.k = k
        heapify(self.h) 
        for i in range(k, len(nums)): 
            self._add(nums[i]) 
         
    def _add(self, val): 
        if len(self.h) < self.k: 
            heappush(self.h, val)` 
        elif val > self.h[0]: 
            heappop(self.h) 
            heappush(self.h, val) 
         
    def add(self, val: int) -> int: 
        self._add(val) 
        return self.h[0]