Search~15 min2s · 256 MBtarget O(n + m) time, O(1) spaceclassic twin: lc-349merge-sorted · two-pointers
A search engine keeps a posting list for every word in its index: the ids of the documents that contain the word. Each list is sorted from the smallest id to the largest, and no id repeats.
A query with two words, such as "parcel tracking", should return only the documents that contain both words. So the search service takes the two words' posting lists and finds the ids that appear in both. The ranking step that comes next expects those ids in increasing order.
Write common_ids(first, second).
first is the posting list of the first word: document ids in strictly increasing order.second is the posting list of the second word, in the same form.Input: first = [4, 9, 12, 20, 27], second = [2, 9, 15, 20, 27, 31]
Output: [9, 20, 27]| i | j | first[i] | second[j] | Compared | Action | common after the step |
|---|---|---|---|---|---|---|
| 0 | 0 | 4 | 2 | second smaller | 2 has no match: j moves | empty |
| 0 | 1 | 4 | 9 | first smaller | 4 has no match: i moves | empty |
| 1 | 1 | 9 | 9 | equal | keep 9: both move | 9 |
| 2 | 2 | 12 | 15 | first smaller | 12 has no match: i moves | 9 |
| 3 | 2 | 20 | 15 | second smaller | 15 has no match: j moves | 9 |
| 3 | 3 | 20 | 20 | equal | keep 20: both move | 9, 20 |
| 4 | 4 | 27 | 27 | equal | keep 27: both move | 9, 20, 27 |
The first list is used up after 27. Document 31 is still in the second list, but nothing is left to match it, so the walk stops.
Input: first = [1, 5, 9], second = [2, 6, 10]
Output: []No document contains both words.
Input: first = [7, 40], second = [3, 7, 18, 40, 52]
Output: [7, 40]The first word is rare. Both of its documents also contain the second word.
1 ≤ first.length ≤ 10^5 and 1 ≤ second.length ≤ 10^51 ≤ first[i], second[j] ≤ 10^9first[i] < first[i + 1] and second[j] < second[j + 1]Checking each id of first against every id of second is O(n × m). With 10^5 ids in each list and no shared ids, that is 10^10 comparisons: far over the budget of about 10^8 simple operations a second. Aim for O(n + m).
Both lists are sorted, and the problem says so for a reason. With one pointer in each list, every comparison rules out at least one id for good.