Fill the blank
Fill the blank so the heap holds the 3 biggest values.
import heapq
keep: list[int] = []
for r in [3, 6, 9, 1, 8, 4]:
heapq.heappush(keep, r)
if ____:
heapq.heappop(keep)
print(sorted(keep), keep[0])Choose an answer, then open Show answer below to check it.
Show answer
Answer: A len(keep) > 3
Right: as soon as there are four, the smallest of them goes.
Capping the heap at k items is what turns O(n log n) into O(n log k).
Why not the others?
- B len(keep) >= 3. That pops when there are three, leaving only two.
- C r > keep[0]. That pops whenever the new value is not the smallest, not when there are too many, so the late 4 stays and it prints [4, 8, 9] 4.