Search~25 min2s · 256 MBtarget O(m + k log m) time, O(m) spacek-way-merge · heaps
A search engine splits its index into shards, and each shard returns its matching results sorted from the best score to the worst. A query goes to all the shards at once.
To fill the results page, the engine needs the k best scores over all the shards, best first. A query can reach 5,000 shards, and each shard can return up to 100,000 scores, but the page shows at most 100,000 of them.
Write top_scores(shards, k).
shards[i] is the list of scores from shard i, in non-increasing order: the best score first. A shard can be empty.k largest scores of all the shards together, from the largest to the smallest. Equal scores count once for each occurrence.k scores in all, return all of them.Input: shards = [[90, 70, 40], [85, 80], [60]], k = 4
Output: [90, 85, 80, 70]Each shard is a sorted list, best first. Keep a heap with the best remaining score of each shard, and pop the best one k times. After each pop, push the next score of the same shard.
| Pop | Score | Pushed next | Heap after the step, best first |
|---|---|---|---|
| 1 | 90 | 70 (shard 0) | 85, 70, 60 |
| 2 | 85 | 80 (shard 1) | 80, 70, 60 |
| 3 | 80 | nothing: shard 1 is done | 70, 60 |
| 4 | 70 | 40 (shard 0) | 60, 40 |
Four scores are out, so we stop. The heap still holds scores that were never needed.
Input: shards = [[5, 5], [5]], k = 10
Output: [5, 5, 5]There are only three scores, so all of them are returned.
Input: shards = [[], [3]], k = 1
Output: [3]The first shard is empty. Its list gives no front.
1 ≤ number of shards ≤ 5,0000 ≤ length of one shard ≤ 10^50 ≤ score ≤ 10^91 ≤ k ≤ 10^5The shards may hold millions of scores in all, but the answer needs only k. A merge that stops after k pops never looks at the rest. With a heap of the shards' fronts, that costs about k × log(number of shards) steps.
Scanning the front of every shard for each of the k scores costs k × shards: 5 × 10^8 for k = 100,000 and 5,000 shards.