Find Kth largest value in a list

Find Kth largest value in a list is pretty self explanatory. However, there will be add() function that will keep on adding new items, and you need to return new Kth item as a new item is added. This problem can be found in leetcode at this link .

Following is a very naaive solution using simple array.

class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.nums = nums self.nums.sort() def add(self, val: int) -> int: self.nums.append(val) self.nums.sort() return self.nums[-1*self.k] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)

The above code is very bad in terms of performance as there is list sorting at each step. We will use heapq in python to solve this problem next.

TODO: Optimize using heapq