Ad platform~20 min2s · 256 MBtarget O(log pushes) time, O(1) spacecomplexity
An ad platform records impressions in a buffer that doubles when it is full. The average cost of a record is small, but each request to record has a latency limit. A record is slow when its own cost is above the limit.
A push costs 1 for the write. A push that finds the buffer full also copies every impression already in it. You will count the slow pushes, which the amortised cost does not show.
Write count_slow_pushes(pushes, start, limit).
start impressions, and pushes impressions arrive one at a time.limit.Input: pushes = 10, start = 1, limit = 3
Output: 2The pushes that resize cost 2, 3, 5 and 9. With a limit of 3, only the costs 5 and 9 are above it.
| Push | Buffer before | Copies | Cost | Slow (limit 3)? |
|---|---|---|---|---|
| 2 | full at 1 | 1 | 2 | no |
| 3 | full at 2 | 2 | 3 | no |
| 5 | full at 4 | 4 | 5 | yes |
| 9 | full at 8 | 8 | 9 | yes |
Every other push costs 1. Two pushes are slow.
Input: pushes = 1000, start = 4, limit = 1
Output: 8With a limit of 1, every resizing push is slow and no other push is. The resizes happen at the capacities 4, 8, 16, 32, 64, 128, 256 and 512 for these 1,000 pushes. That makes 8 slow pushes.
Input: pushes = 3, start = 5, limit = 2
Output: 0Three pushes fit in room for five, so no push resizes and none is slow: 0.
0 ≤ pushes ≤ 1,000,000,000 (impressions)1 ≤ start ≤ 1,000 (starting room)1 ≤ limit ≤ 1,000,000,000 (cost of a push)Pricing every push costs up to 10^9 steps. Only the pushes that resize can cost more than 1, and there are about 30 of them. Count those, with the right comparison.