Data Structures & AlgorithmsHardProduct Company SDE · heap round

Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3?

Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3?
import heapq
def kth(a, k):
    h = []
    for x in a:
        heapq.heappush(h, x)
        if len(h) > k:
            heapq.heappop(h)
    return h[0]
print(kth([7, 10, 4, 3, 20, 15], 3))
  1. A. 4
  2. B. 7
  3. C. 10
  4. D. 15

Correct answer: C. 10

A min-heap capped at size k keeps the k largest values {10, 15, 20}, and its root 10 is the 3rd largest. Returning the root of a max-heap or the 3rd smallest value are the traps.

More Coding Interview Problems questions

Exams that ask this topic