Music streaming app~20 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-278binary-search
A music streaming app ships builds in order. For each build, the monitoring system records two health measures from a canary group: the number of playback errors per 10,000 plays, and the startup time in milliseconds.
Regressions pile up from build to build, so neither measure ever falls. A build is unhealthy when its errors pass one limit, or its startup time passes another. Teams ask for the first unhealthy build under many pairs of limits.
Write first_unhealthy(errors, slow, limits).
errors[v] and slow[v] are the two measures of build v. Both never fall as v grows.[max_errors, max_slow] makes build v unhealthy when errors[v] > max_errors or slow[v] > max_slow.Input: errors = [1, 2, 2, 4, 7, 9, 15, 20], slow = [300, 310, 350, 360, 380, 500, 520, 700], limits = [[5, 400], [20, 400], [0, 300], [100, 1000], [3, 320], [8, 360]]
Output: [4, 5, 0, -1, 2, 4]Take the pair [20, 400]. The check on a build is: errors above 20, or startup above 400. Neither measure falls, so once a build is unhealthy, every later build is too. Search the window [lo, hi) of builds, starting as [0, 8).
| Step | lo | hi | mid | errors | slow | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 7 | 380 | healthy, so lo = 5 |
| 2 | 5 | 8 | 6 | 15 | 520 | unhealthy (slow 520 > 400), so hi = 6 |
| 3 | 5 | 6 | 5 | 9 | 500 | unhealthy (slow 500 > 400), so hi = 5 |
| end | 5 | 5 | the first unhealthy build is 5 |
The errors never pass 20, so the startup time decides this pair. The pair [100, 1000] is never passed, so its answer is -1.
Input: errors = [3], slow = [10], limits = [[3, 10], [2, 10], [3, 9]]
Output: [-1, 0, 0]The limits are inclusive: a value equal to the limit is still healthy.
Input: errors = [0, 0, 5, 5], slow = [100, 200, 200, 900], limits = [[4, 500], [5, 500], [5, 900]]
Output: [2, 3, -1]For [4, 500] the errors pass the limit at build 2. For [5, 500] the startup time passes it at build 3.
1 ≤ errors.length = slow.length ≤ 100,0000 ≤ errors[v] ≤ 10,000 and 0 ≤ slow[v] ≤ 100,000errors and slow never fall from one build to the next0 ≤ limits.length ≤ 100,000[max_errors, max_slow] holds numbers in the same ranges as the measuresScanning the builds for every pair of limits costs up to 10^5 steps a pair, so 10^10 steps for 10^5 pairs. The check is monotone, so one halving search with the combined check needs about 17 looks per pair, which is under 2 × 10^6 in all.