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?
- 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
- B. Maintain a min-heap of size k, pushing each element and popping when the heap exceeds size k: O(n log k)
- C. Scan the array k times, each time removing the current maximum: O(nk)
- 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
- Problem: An LRU (Least Recently Used) cache with O(1) get and put operations is classically implemented with which combination of data…
- Problem: Which statement about Kruskal's algorithm's overall time complexity is correct for a graph with V vertices and E edges?
- Problem: Topological sort is only defined for which kind of graph, and what happens if Kahn's algorithm is run on a graph that violates…
- Problem: Which best explains why merge sort is preferred over quicksort for sorting linked lists (as opposed to arrays)?
- Problem: Which best explains the time complexity difference between recursive (top-down with memoization) and iterative (bottom-up…
- Problem: What is the time complexity of building a trie from n words with total character count L, and what is the space complexity?