Search~15 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-704binary-search
A search engine keeps the ids of the documents that contain a word in one list. The list is sorted from the smallest id to the largest, and no id appears twice.
Support engineers paste in many document ids and ask: where is this id in the list? The answer is its position, counting from 0, or -1 when the id is not in the list.
Write find_ids(ids, queries).
ids is the sorted list of document ids, with no repeats.queries is the list of ids to look for.ids, or -1 when it is missing.Input: ids = [3, 8, 12, 20, 31], queries = [20, 5, 40, 3]
Output: [3, -1, -1, 0]Take the query 20. The search window is the half-open range [lo, hi), which starts as [0, 5).
| Step | lo | hi | mid | ids[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 12 | 12 < 20, so lo = 3 |
| 2 | 3 | 5 | 4 | 31 | 31 is not below 20, so hi = 4 |
| 3 | 3 | 4 | 3 | 20 | 20 is not below 20, so hi = 3 |
| end | 3 | 3 | ids[3] is 20, so the answer is 3 |
The query 5 ends with lo = 1, where ids[1] is 8, so it is missing. The query 40 ends with lo = 5, past the end. The query 3 ends with lo = 0, where ids[0] is 3.
Input: ids = [], queries = [4]
Output: [-1]An empty list has no ids, so every query is missing.
Input: ids = [2, 4, 6, 8], queries = [8, 1, 9, 6]
Output: [3, -1, -1, 2]The last id (position 3) is found. A query below every id and a query above every id are both missing.
0 ≤ ids.length ≤ 100,000, and ids is strictly increasing: sorted, with no repeats0 ≤ queries.length ≤ 100,0000 ≤ ids[i], queries[j] ≤ 1,000,000,000Looking at every id for every question costs about n × q steps, which is 10^10 when both are 100,000. A binary search costs about log n steps per question, which is 17 at n = 100,000.