Search~25 min2s · 256 MBtarget O(q log m) time, O(q) spaceclassic twin: lc-702binary-search
A search service keeps the ids of its documents in an index file that only grows. New ids are always larger than the ones before, so the file stays sorted from the smallest id to the largest.
The file does not store how many ids it holds. A read at a position after the last id returns the end marker 1,000,000,000, which is larger than every id. Reading further past the end returns the marker again.
You answer lookup requests: for each id a user asks about, you report its position in the index, or -1 when it is not there.
Write find_in_open_index(entries, targets).
entries is a snapshot of the file: the ids from the smallest to the largest, strictly rising, followed by at least one end marker.targets[j], return its position, counting from 0, or -1 when no entry equals it.targets.Input: entries = [3, 8, 15, 21, 34, 55, 89, 144, 1000000000, 1000000000], targets = [89]
Output: [6]The trace first doubles a probe position until the entry there is not below 89, then searches the window that the probe left behind. The window has lo as its start and hi as its end, and a read past the end gives the marker.
| Step | lo | hi | Position read | Entry | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 8 | below 89: move lo to 1, double hi to 2 |
| 2 | 1 | 2 | 2 | 15 | below 89: move lo to 2, double hi to 4 |
| 3 | 2 | 4 | 4 | 34 | below 89: move lo to 4, double hi to 8 |
| 4 | 4 | 8 | 8 | 1000000000 | not below 89: the window is 4 to 8 |
| 5 | 4 | 8 | 6 | 89 | at least 89: hi becomes 6 |
| 6 | 4 | 6 | 5 | 55 | below 89: lo becomes 6 |
The window closes at position 6, and the entry there is 89, so the answer is 6.
Input: entries = [3, 8, 15, 1000000000], targets = [4, 3, 16]
Output: [-1, 0, -1]The ids 4 and 16 are not in the index. The id 3 is the first entry.
Input: entries = [1000000000], targets = [5]
Output: [-1]The index is empty: position 0 already holds the end marker.
1 ≤ entries.length ≤ 200,000, ending with at least one marker 1,000,000,0001 ≤ targets.length ≤ 100,0001 ≤ targets[j] ≤ 999,999,999A scan from position 0 costs up to 200,000 reads for one lookup, so 100,000 lookups cost up to 2 × 10^10 reads in the worst case. That is far over the budget of about 10^8 a second. Each lookup must cost a few dozen reads at most, so the search has to halve a window.