Engineering platform~22 min2s · 256 MBtarget O(n) time, O(1) spacesliding-window-variable · two-pointers
You work on a hosting platform. For each minute of a day, a log holds the data transferred by a customer, in whole units. A billing rule looks at windows of consecutive minutes.
A window is in the allowance band when its total is at least low and at most high. Your team lead asks: "How many windows of one or more consecutive minutes fall in the band?" A day's log can hold 100,000 minutes.
Write count_windows_in_band(usage, low, high).
usage[i] is the data transferred in minute i. It is never negative.low and at most high.Input: usage = [3, 1, 4, 1, 5], low = 4, high = 6
Output: 7Count the windows with a total of at most 6, and subtract those with a total of at most 3. The difference is the windows with a total from 4 to 6.
| Minutes | Usage | Total |
|---|---|---|
| 0 to 1 | [3, 1] | 4 |
| 1 to 2 | [1, 4] | 5 |
| 1 to 3 | [1, 4, 1] | 6 |
| 2 to 2 | [4] | 4 |
| 2 to 3 | [4, 1] | 5 |
| 3 to 4 | [1, 5] | 6 |
| 4 to 4 | [5] | 5 |
There are 10 windows with a total of at most 6, and 3 windows with a total of at most 3. The difference is 7.
Input: usage = [0, 0, 0], low = 0, high = 0
Output: 6Every window has a total of 0, and the band is exactly 0. All 6 windows count.
Input: usage = [5, 5], low = 6, high = 9
Output: 0The windows have totals 5, 5 and 10. None falls between 6 and 9.
1 ≤ len(usage) ≤ 100,0000 ≤ usage[i] ≤ 1,000,0000 ≤ low ≤ high ≤ 100,000,000,000A log of 100,000 minutes has almost 5 billion windows, so adding up each one is too slow for a 2-second limit. All values are non-negative, so a window only gets bigger when it grows to the right. That lets two pointers find, for each end, how many starts are allowed, in one pass of about 100,000 steps.