Monitoring~20 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-34binary-search
A monitoring system turns a day of logs into an index of error codes. The index has one entry for every log line, sorted from the smallest code to the largest. A busy code appears on many lines, so equal codes sit side by side.
Engineers ask about one code at a time: which block of positions in the index holds it?
Write occurrences(codes, queries).
codes is the sorted index, with repeats allowed. Positions count from 0.[first, last] for each query, in order. When the code is not in the index, the pair is [-1, -1].Input: codes = [5, 7, 7, 7, 9, 9, 12], queries = [7, 9, 8, 12]
Output: [[1, 3], [4, 5], [-1, -1], [6, 6]]Take the code 7. The start of its block is the first position whose code is not below 7. The end is one before the first position whose code is not below 8. Both searches use the window [lo, hi), which starts as [0, 7).
| Search | lo | hi | mid | codes[mid] | Decision |
|---|---|---|---|---|---|
| not below 7 | 0 | 7 | 3 | 7 | not below 7, so hi = 3 |
| not below 7 | 0 | 3 | 1 | 7 | not below 7, so hi = 1 |
| not below 7 | 0 | 1 | 0 | 5 | 5 < 7, so lo = 1 (start = 1) |
| not below 8 | 0 | 7 | 3 | 7 | 7 < 8, so lo = 4 |
| not below 8 | 4 | 7 | 5 | 9 | not below 8, so hi = 5 |
| not below 8 | 4 | 5 | 4 | 9 | not below 8, so hi = 4 (stop = 4) |
The code 7 fills positions 1 to 3, so the pair is [1, 3]. The code 8 has the same start and stop, 4, so it is missing.
Input: codes = [], queries = [3]
Output: [[-1, -1]]An empty index holds no code.
Input: codes = [4, 4, 4, 4], queries = [4, 3, 5]
Output: [[0, 3], [-1, -1], [-1, -1]]When every entry is equal, the block is the whole list, [0, 3]. A code below it and a code above it are both missing.
0 ≤ codes.length ≤ 100,000, and codes is sorted from smallest to largest, repeats allowed0 ≤ queries.length ≤ 100,0000 ≤ codes[i], queries[j] ≤ 1,000,000,000Scanning the whole list for every code costs about n × q steps, which is 10^10 when both are 100,000. Two binary searches per code cost about 34 steps. The repeats matter: a list can hold 100,000 copies of one code, so you cannot walk outwards from one match.