Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have arrived.
Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have arrived.
import heapq
def run(stream, k):
h, out = [], []
for x in stream:
heapq.heappush(h, x)
if len(h) > k: heapq.heappop(h)
if len(h) == k: out.append(h[0])
return out
print(run([5, 1, 9, 3, 7, 8], 3))What is printed?- A. [1, 3, 5, 8]
- B. [9, 9, 9, 9]
- C. [1, 3, 5, 7]
- D. [5, 5, 7, 8]
Correct answer: C. [1, 3, 5, 7]
After 5, 1, 9 the heap holds {1, 5, 9} with top 1. Adding 3 evicts 1 (top 3), adding 7 evicts 3 (top 5), adding 8 evicts 5 (top 7). The heap root is the smallest of the k largest, which is exactly the k-th largest.
More Coding Interview Problems questions
- Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by…
- Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes. python def…
- How many structurally different binary search trees can be built on the keys 1..7 if the ROOT must be 3?
- Problem: Count the ways to tile a 2 × n board with 2 × 1 dominoes and L-shaped trominoes (both rotatable). python def tilings(n): dp = [1…
- What is the time complexity of this loop? python i = n while i > 0: for j in range(i): work() # O(1) i //= 2
- Recursive quicksort can need O(n) stack depth on adversarial input. Which change GUARANTEES O(log n) extra stack space even in the worst…