Engineering platform~20 min2s · 256 MBtarget O(q log n) time, O(1) spacebinary-search
You work on the engineering platform behind an app. A bug entered the code in one commit and stays in every later commit of its service. Each commit gets the same test several times.
The test is flaky. A good commit never fails it. A bad commit fails only some of its runs, so one failed run proves the commit is bad, but a pass proves nothing. You are told, for each commit, how many runs failed.
Write first_bad_commits(fails, ranges).
fails[c] is the number of failed runs of commit c. A commit is bad when at least one run failed.[a, b] names a commit a known to be good and a later commit b known to be bad.Input: fails = [0, 0, 0, 0, 2, 1, 1, 3, 1, 2, 1, 4], ranges = [[0, 11], [1, 9], [2, 5], [3, 4]]
Output: [4, 4, 4, 4]Take the range [0, 11]. Commit 0 is good and commit 11 is bad, so the first bad commit is in the window [1, 11), with 11 as a commit that surely fails. The check on a commit is: did at least one run fail?
| Step | lo | hi | mid | fails[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 11 | 6 | 1 | a run failed, so hi = 6 |
| 2 | 1 | 6 | 3 | 0 | no run failed, so lo = 4 |
| 3 | 4 | 6 | 5 | 1 | a run failed, so hi = 5 |
| 4 | 4 | 5 | 4 | 2 | a run failed, so hi = 4 |
| end | 4 | 4 | the first bad commit is 4 |
All four ranges contain commit 4 and start before it, so every answer is 4.
Input: fails = [0, 3], ranges = [[0, 1]]
Output: [1]The only commit after the good one is the bad one.
Input: fails = [0, 0, 1, 0, 0, 5, 2, 1], ranges = [[0, 2], [3, 7], [3, 5]]
Output: [2, 5, 5]The history holds two services side by side. The range [0, 2] ends at its first failure. The ranges [3, 7] and [3, 5] belong to the second service, whose first bad commit is 5.
1 ≤ fails.length ≤ 100,000 and 0 ≤ fails[c] ≤ 100 ≤ ranges.length ≤ 100,000. For each range [a, b]: 0 ≤ a < b < fails.length, fails[a] = 0 and fails[b] > 0Scanning a range commit by commit costs up to its length, and ranges can be long: 10^5 ranges of 10,000 commits make 10^9 steps. A search that halves the range needs about 14 steps per range, so about 1.4 × 10^6 steps in all.