Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: To find the k largest elements among n numbers, which approach is asymptotically best when k is much smaller than n?

  1. A. Build a max-heap of all n elements and pop k times: O(n + k log n), which is worse for small k vs n
  2. B. Maintain a min-heap of size k, pushing each element and popping when the heap exceeds size k: O(n log k)
  3. C. Scan the array k times, each time removing the current maximum: O(nk)
  4. D. Sort the whole array and take the last k: O(n log n)

Correct answer: B. Maintain a min-heap of size k, pushing each element and popping when the heap exceeds size k: O(n log k)

A size-k min-heap only ever holds the k largest-so-far; each of the n elements triggers at most one O(log k) heap operation, giving O(n log k), which beats both full sorting and an O(nk) repeated-max scan when k is small.

More Coding Interview Problems questions

Exams that ask this topic