heap = []
for num in nums:
heapq.heappush(heap, num)
can be reduced to below code, will have O(N) complexity
heapq.heapify(nums)
while this given code -
for _ in xrange(len(nums)-k):
heapq.heappop(heap)
return heapq.heappop(heap)
can be reduced to below code, will have complexity O(log(n-k))
return heapq.nsmallest(n-k, nums)[0]
For more info on what's the complexity of each function, read - https://dpythoncodenemesis.medium.com/understanding-pythons-heapq-module-a-guide-to-heap-queues-cfded4e7dfca