Social feed~20 min2s · 256 MBtarget O(q log n) time, O(1) spacebinary-search
A social app counts, each day, how many feed loads were requested and how many of them failed. After a bad release the failure rate climbs and never recovers by itself, so the daily rate never falls from one day to the next.
Teams set alert limits as fractions, such as 3 in 100. For each limit, they want the first day on which the failure rate was above it.
Write first_day_over(fails, loads, limits).
fails[d] of the loads[d] feed loads of day d failed. The rate fails[d] / loads[d] never falls as d grows.[num, den] is the fraction num / den. Day d is over the limit when fails[d] / loads[d] is above num / den, not equal to it.Input: fails = [0, 10, 15, 60, 75, 160], loads = [1000, 2000, 1500, 3000, 2500, 4000], limits = [[1, 100], [3, 100], [1, 50], [1, 10], [0, 1], [1, 200]]
Output: [3, 5, 4, -1, 1, 2]The daily rates are 0, 0.005, 0.01, 0.02, 0.03 and 0.04. To compare a rate with num / den without division, compare fails × den with loads × num. Take the limit [3, 100]. The window [lo, hi) starts as [0, 6).
| Step | lo | hi | mid | fails × den | loads × num | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 60 × 100 = 6000 | 3000 × 3 = 9000 | not above the limit, so lo = 4 |
| 2 | 4 | 6 | 5 | 160 × 100 = 16000 | 4000 × 3 = 12000 | above the limit, so hi = 5 |
| 3 | 4 | 5 | 4 | 75 × 100 = 7500 | 2500 × 3 = 7500 | not above the limit, so lo = 5 |
| end | 5 | 5 | the first day over 3 in 100 is day 5 |
On day 4 the rate is exactly 0.03, which is equal to the limit, not above it. The limit [0, 1] is a rate of 0, so the first day with any failure is day 1.
Input: fails = [1], loads = [2], limits = [[1, 2], [499999, 1000000]]
Output: [-1, 0]A rate equal to the limit is not over it. On day 0 the rate is 0.5, which is above 0.499999.
Input: fails = [0, 0, 1, 3], loads = [5, 9, 9, 10], limits = [[0, 1], [1, 10], [1, 5]]
Output: [2, 2, 3]The rates are 0, 0, about 0.11 and 0.3. The first day with any failure is day 2, and 0.11 is also above 0.1. The rate 0.3 is above 0.2 only on day 3.
1 ≤ fails.length = loads.length ≤ 100,0000 ≤ fails[d] ≤ loads[d] ≤ 1,000,000,000 and loads[d] ≥ 1fails[d] / loads[d] never falls from one day to the next0 ≤ limits.length ≤ 100,000[num, den] has 0 ≤ num ≤ den ≤ 1,000,000 and den ≥ 1A day's loads can be 10^9 and a limit's denominator 10^6, so a product can reach 10^15. That does not fit a 32-bit integer, and Java and C++ need a 64-bit integer. Scanning the days for every limit costs up to 10^5 steps a limit, so 10^10 steps for 10^5 limits. A halving search costs about 17.