LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Coding Problems – Data Structures and Algorithms · Question 7

K-th largest element using a size-k min-heap in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Find the k-th largest element of a list by keeping a min-heap of size k, and also track it for a stream of new numbers.

Solution
main.py Run
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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links