Intuition
Here, the stream
means that numbers could be added onto it.
Since we are asked K-th largest, we use a min-heap keep track of the current largest element heap[0]
.
We don’t really care when our len(heapq)
exceeds k
because those element are anyway too small. So since we are doing the def add(self, val)
operation, elements are only going to get added not subtracted.
Then in our def add(self, val)
method, we remove the smallest element when a
PS:
python3
by default has a min-heap implementedheapq
Code:
Python
Big O Analysis
-
Runtime
The runtime complexity here is since
heapify
takes linear time, theadd
function takes time.:w -
Memory
The memory usage is since we are maintaining a heap of K elements.
— A