Kth Largest Element in a Stream
Problem Summary
- Given a list of
nums and also a stream of incoming values. Define a class with __init__ and add() that returns the largest element
Approach Taken
- Use a min heap to always keep values and return largest element in
- This lets us achieve for our
add()
Why This Works
- Heap has
push or pop
Main Concepts Used
Time & Space Complexity
- Time for init: → Reason: Initial heapify is , however reducing the size of the heap to is and
pops of times
- Time for add: → Reason: In the worst case, we will do both
pop and push
- Space: → Reason: We will only store items in our min heap
Code
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.minHeap, self.k = nums, k
heapq.heapify(self.minHeap)
while len(self.minHeap) > k:
heapq.heappop(self.minHeap)
def add(self, val: int) -> int:
if len(self.minHeap) < self.k:
heapq.heappush(self.minHeap, val)
elif val > self.minHeap[0]:
heapq.heappush(self.minHeap, val)
heapq.heappop(self.minHeap)
return self.minHeap[0]
Common Mistakes / Things I Got Stuck On
- Not setting member variables correctly
self.{variable}