#703
Kth Largest Element in a Stream
easy· Heap / Priority Queueruns: 0Design a class that finds the kth largest element in a stream. Implement KthLargest(k, nums) which initializes the class with the integer k and the stream nums, and add(val) which appends val to the stream and returns the kth largest element seen so far.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 406
import heapq
class KthLargest:
def __init__(self, k: int, nums: list[int]):
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.