Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the k-th largest value in a stream of scores using a min-heap of size k.

Problem: Return the k-th largest value in a stream of scores using a min-heap of size k.
import heapq
def kth_largest(a, k):
    h = []
    for x in a:
        heapq.heappush(h, x)
        if len(h) > k: heapq.heappop(h)
    return h[0]
print(kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4), kth_largest([7, 7, 7], 2))
What is printed?
  1. A. 4 7
  2. B. 5 7
  3. C. 3 7
  4. D. 4 0

Correct answer: A. 4 7

The heap keeps the k largest values seen; its root is the smallest of them, i.e. the k-th largest. Sorted descending the first list is 6, 5, 5, 4, … so the 4th largest is 4 (duplicates count separately). For [7, 7, 7] the 2nd largest is 7. O(n log k) time, O(k) space – better than sorting when k ≪ n.

More Coding Interview Problems questions

Exams that ask this topic