Usually, the problem description on platforms like LeetCode will provide sufficient details that:
We will use a min-heap (priority queue) of fixed size k
to efficiently track the Kth largest element.
k
elements.k
elements initially, initialize the heap with all elements.k
elements, add the new element directly to the heap.import heapq
class KthLargest:
def __init__(self, k: int, nums: list):
self.k = k
self.min_heap = []
for num in nums:
self.add(num)
def add(self, val: int) -> int:
if len(self.min_heap) < self.k:
heapq.heappush(self.min_heap, val)
elif val > self.min_heap[0]:
heapq.heapreplace(self.min_heap, val)
return self.min_heap[0]
# Example usage:
# kthLargest = KthLargest(3, [4, 5, 8, 2])
# print(kthLargest.add(3)) # returns 4
# print(kthLargest.add(5)) # returns 5
# print(kthLargest.add(10)) # returns 5
# print(kthLargest.add(9)) # returns 8
# print(kthLargest.add(4)) # returns 8
n
elements where n
is the number of elements: O(n log k)
.k
: O(log k)
.O(1)
.KthLargest
class maintains a min-heap of size k
to keep track of the Kth largest element efficiently.add
method ensures we maintain the correct heap size and immediately provide the Kth largest element after each insertion.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?