Engineering platform~12 min2s · 256 MBtarget O(q log b) time, O(1) spaceclassic twin: lc-278binary-search
A build system builds an app every time code is merged. For each service of the app it keeps the test results, one for each build, oldest build first. A result is 0 when the service's tests pass and 1 when they fail.
When a change breaks a service, the break stays in the code. The service fails on that build and on every later build, until someone merges a fix. These histories end before any fix.
Engineers ask which build first broke the services they care about.
Write first_failures(results, services).
results[s] is the history of service s, and results[s][b] is the result of build b, which is 0 or 1. In one history, no 1 is followed by a 0.services lists the services that engineers ask about. A service can be asked about more than once. Every entry is a valid index into results.services, in order.Input: results = [[0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1], [0, 1]], services = [0, 1, 2, 3, 0]
Output: [3, -1, 0, 1, 3]Take service 0, which has 8 builds. The window [lo, hi) holds the builds that might be the first failing one.
| Step | lo | hi | mid | results[0][mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 1 | build 4 fails, so hi = 4 |
| 2 | 0 | 4 | 2 | 0 | build 2 passes, so lo = 3 |
| 3 | 3 | 4 | 3 | 1 | build 3 fails, so hi = 3 |
| end | 3 | 3 | build 3 is the first failing build |
Service 1 never fails, so its answer is -1. Service 2 fails from the very first build. Service 3 fails from build 1.
Input: results = [[]], services = [0, 0]
Output: [-1, -1]A service with no builds has no failing build, and asking twice gives the same answer twice.
Input: results = [[0], [1], [0, 0, 1]], services = [2, 1, 0, 2]
Output: [2, 0, -1, 2]Service 2 fails only on its last build. Service 1 has one build, and it fails. Service 0 has one build, and it passes.
0 ≤ results.length ≤ 1,0000 ≤ results[s].length ≤ 100,000, and each result is 0 or 10 ≤ services.length ≤ 100,000, and every entry is a valid index into resultsA history can hold 10^5 builds and there can be 10^5 questions. Scanning a history from its first build costs up to 10^5 steps for each question, which is 10^10 steps in all. In one history the results never go back from 1 to 0, so the first 1 can be found with about 17 checks.