ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
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, 1, 5, 6, 4], 2), kth_largest([7], 1))
  1. A. 6 7
  2. B. 4 7
  3. C. 5 7
  4. D. 5 1

Correct answer: C. 5 7

A min-heap of size k keeps the k largest values seen so far, so its root is the k-th largest. For [3,2,1,5,6,4] and k=2 that is 5, and for [7] it is 7.

More Python Programming questions

Exams that ask this topic