Engineering platform~25 min2s · 256 MBtarget O(n) time, O(n) spacesliding-window-variable · queues
A software platform meters its API. Each customer has two quotas that roll forward with time: a total cost per minute, and a total cost per hour. A request has a cost, because some calls are heavier than others.
A request is accepted only if both quotas still have room for it. A rejected request is not served, so it uses no quota. The platform needs to know which requests were accepted.
Write allowed_requests(times, costs, minute_limit, hour_limit).
i arrives at second times[i] and costs costs[i]. The requests are listed in the order they arrive, so times never goes down.t holds the accepted requests at seconds s with t - s < 60. The hour window holds those with t - s < 3600.i is accepted when two tests hold. The cost in the minute window plus costs[i] is at most minute_limit. The cost in the hour window plus costs[i] is at most hour_limit.Input: times = [0, 10, 30, 61, 62, 200, 3000, 3601], costs = [4, 5, 3, 2, 6, 9, 1, 8], minute_limit = 10, hour_limit = 20
Output: [1, 1, 0, 1, 0, 1, 0, 0]The trace shows the cost of the accepted requests in each window before the request arrives.
| i | Second | Cost | Minute window | Hour window | Result |
|---|---|---|---|---|---|
| 0 | 0 | 4 | 0 | 0 | accepted |
| 1 | 10 | 5 | 4 | 4 | accepted |
| 2 | 30 | 3 | 9 | 9 | rejected: 9 + 3 is above 10 |
| 3 | 61 | 2 | 5 | 9 | accepted: the request at second 0 left the minute window |
| 4 | 62 | 6 | 7 | 11 | rejected: 7 + 6 is above 10 |
| 5 | 200 | 9 | 0 | 11 | accepted |
| 6 | 3000 | 1 | 0 | 20 | rejected: 20 + 1 is above 20 |
| 7 | 3601 | 8 | 0 | 16 | rejected: 16 + 8 is above 20 |
The output is [1, 1, 0, 1, 0, 1, 0, 0]. At second 3601, the request at second 0 has left the hour window, and the requests at seconds 10, 61 and 200 are still in it.
Input: times = [5, 5, 5], costs = [4, 4, 4], minute_limit = 8, hour_limit = 100
Output: [1, 1, 0]Two requests of cost 4 fit in a minute limit of 8, and the third would make 12. All three arrive in the same second.
Input: times = [0, 60], costs = [10, 10], minute_limit = 10, hour_limit = 100
Output: [1, 1]The second request arrives exactly 60 seconds after the first, so the first has left the minute window.
1 ≤ times.length ≤ 100,000 (requests); costs has the same length0 ≤ times[i] ≤ 2,678,400 (seconds in a month), never going down1 ≤ costs[i] ≤ 1001 ≤ minute_limit ≤ 10,000, 1 ≤ hour_limit ≤ 1,000,000Adding up all earlier accepted requests for every request costs about n × n / 2 steps, about 5 × 10^9. Both windows end at the current request and start further back, and the starts only move forward in time. So each window needs a start position and a running total, and every request is added and dropped once.