Engineering platform~25 min2s · 256 MBtarget O(log n + q log n) time, O(1) spaceclassic twin: lc-33binary-search
A database cluster keeps its shard ids in a config file in increasing order. After a rolling restart, the file is rewritten starting from the shard that restarted first, so the list is rotated: for example 40, 50, 60, 10, 20, 30.
Operators look up many shard ids. For each id, they want its position in the file, or -1 if the cluster has no such shard.
Write find_in_rotated(shards, queries).
shards has distinct ids. It is a sorted list that was rotated by some amount, possibly 0.shards, or -1 when it is missing.Input: shards = [40, 50, 60, 10, 20, 30], queries = [20, 60, 10, 45, 70, 0]
Output: [4, 2, 3, -1, -1, -1]First find the pivot, the position of the smallest id. Compare the middle with the last id: if the middle is larger, the smallest id is to its right. Then search for each id on the positions as if the list were sorted, mapping a virtual position v to the real position (v + pivot) % n.
| Step | lo | hi | mid | shards[mid] | shards[hi] | Decision |
|---|---|---|---|---|---|---|
| pivot 1 | 0 | 5 | 2 | 60 | 30 | 60 > 30, so lo = 3 |
| pivot 2 | 3 | 5 | 4 | 20 | 30 | 20 > 30 is false, so hi = 4 |
| pivot 3 | 3 | 4 | 3 | 10 | 20 | 10 > 20 is false, so hi = 3 |
The pivot is 3, where the smallest id, 10, sits. Now search for the id 20 in the virtual window [0, 6).
The middle 3 is the real position 0, holding 40. That is not below 20, so hi = 3. The middle 1 is the real position 4, holding 20, which is not below 20, so hi = 1.
The middle 0 is the real position 3, holding 10, which is below 20, so lo = 1. The virtual position 1 is the real position 4, and it holds 20, so the answer is 4.
The ids 60 and 10 are at the positions 2 and 3. The ids 45, 70 and 0 are missing, so the answer is [4, 2, 3, -1, -1, -1].
Input: shards = [], queries = [5]
Output: [-1]An empty list has no shard.
Input: shards = [1, 2, 3], queries = [1, 3, 0]
Output: [0, 2, -1]A rotation of 0 leaves the list sorted, and the pivot is 0. The ids 1 and 3 are found at the ends, and 0 is missing.
0 ≤ shards.length ≤ 100,000, and all ids are differentshards is a list in increasing order that was rotated: the first part moved to the end. A rotation of 0 is allowed0 ≤ queries.length ≤ 100,0000 ≤ shards[i], queries[j] ≤ 1,000,000,000Scanning the whole list for every id costs about n × q steps, which is 10^10 when both are 100,000. The list is almost sorted, so a binary search can still work after you find where the rotation happened. That takes about 17 steps, once, and then about 17 steps per id.