import heapq
def kth_largest(nums, k):
heap = nums[:k]
heapq.heapify(heap) # the k largest seen so far; heap[0] is the k-th largest
for n in nums[k:]:
if n > heap[0]:
heapq.heapreplace(heap, n) # pop the smallest and push n in one step
return heap[0]
print(kth_largest([3, 2, 1, 5, 6, 4], 2), kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4))
stream_heap = [4, 5, 8] # k = 3
heapq.heapify(stream_heap)
for x in [3, 5, 10, 9, 4]:
if x > stream_heap[0]:
heapq.heapreplace(stream_heap, x)
print(x, "->", stream_heap[0])
Output Verified by running it on Python 3
5 4
3 -> 4
5 -> 5
10 -> 5
9 -> 8
4 -> 8
The heap holds the k largest values; its minimum is the answer. O(n log k) time, O(k) space – better than sorting when k is small.
More Python Coding Interview Questions practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!