linkjobai / Top-K Problems with Heaps: When and How to Use Them
0 вподобань
0 форк(-ів)
1 файл(-ів)
Остання активність 5 days ago
Interview prep notes
Top-K Problems with Heaps: When and How to Use Them
"Find the k most frequent elements", "k closest points to the origin", "kth largest element in a stream": whenever a question says top k, consider a heap.
Rule of thumb
To keep the k largest items, use a min-heap of size k. The smallest of your current top k sits at the root, so each new item is compared with it in O(log k).
import heapq
Новіше
Пізніше