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?- A. 4 7
- B. 5 7
- C. 3 7
- 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
- Problem: From n = 10⁶ log entries, return the k = 10 most frequent error codes. Which approach is the most efficient?
- Problem: Merge k sorted lists of order timestamps into one sorted list. python import heapq def mergek(lists): h = [(l[0], i, 0) for i, l…
- Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half). python import heapq…
- Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost. python import heapq def…
- Problem: Return the k points closest to the origin (ties broken by smaller index). python import heapq pts = [(3, 3), (5, -1), (-2, 4)…
- Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time. python…