Search~30 min2s · 256 MBtarget O(n log k) time, O(k) spacek-way-merge
You work on a search engine. For each word of a query, the index keeps a list of the documents that contain the word. The ids in a list are in increasing order, and a document appears once in a list.
A query can say: "a document matches when it contains at least need of these words". Your team lead asks: "Which documents match, in increasing id order?" The lists hold up to 200,000 ids in all, and a query can have thousands of words.
Write matched_documents(lists, need).
lists[i] is the list of document ids for query word i. Each list is strictly increasing and not empty.need different lists.Input: lists = [[1, 4, 9, 12], [2, 4, 6, 9], [4, 5, 9, 12, 14], [6, 9]], need = 2
Output: [4, 6, 9, 12]| Smallest document | Lists that hold it | Count | Kept |
|---|---|---|---|
| 1 | 0 | 1 | no |
| 2 | 1 | 1 | no |
| 4 | 0, 1, 2 | 3 | yes |
| 5 | 2 | 1 | no |
| 6 | 1, 3 | 2 | yes |
| 9 | 0, 1, 2, 3 | 4 | yes |
| 12 | 0, 2 | 2 | yes |
| 14 | 2 | 1 | no |
Input: lists = [[5], [5]], need = 2
Output: [5]Input: lists = [[3, 8]], need = 2
Output: []There is only one list, so no document appears in two lists. need can be larger than the number of lists.
1 ≤ lists.length ≤ 5,000 (query words)1 ≤ lists[i].length, and all lists together hold at most 200,000 ids1 ≤ need ≤ 5,000Looking at the front of every list to find the smallest document costs one step for each list. For each of up to 200,000 distinct documents, that is 5,000 steps, or about 1,000,000,000 steps.
A heap holds the front of each list, and finds the smallest in about 13 steps. Each id is pushed and popped once, so 200,000 ids cost about 5,000,000 steps.