Ride-hailing app~15 min2s · 256 MBtarget O(log pushes) time, O(1) spacecomplexity
A ride-hailing app keeps incoming ride requests in a buffer. The buffer starts with room for a fixed number of requests. When a request arrives and the buffer is full, the app allocates a buffer with twice the room and copies every request across before adding the new one.
The copying is the slow part. The team wants the total number of requests copied over a busy hour, without running the buffer.
Write total_copies(pushes, start).
start requests. pushes requests arrive one at a time.Input: pushes = 10, start = 1
Output: 15The buffer holds 1 request at first, and doubles whenever a push finds it full.
| Push | Buffer before | Copies | Buffer after |
|---|---|---|---|
| 2 | full at 1 | 1 | room for 2 |
| 3 | full at 2 | 2 | room for 4 |
| 5 | full at 4 | 4 | room for 8 |
| 9 | full at 8 | 8 | room for 16 |
The other pushes copy nothing. The total is 1 + 2 + 4 + 8 = 15.
Input: pushes = 100, start = 4
Output: 124The room goes 4, 8, 16, 32, 64, 128. The resizes copy 4, 8, 16, 32 and 64 requests, and the 100 pushes fit in 128 slots. The total is 124.
Input: pushes = 0, start = 5
Output: 0With no pushes, nothing is copied: 0.
0 ≤ pushes ≤ 1,000,000,000 (requests)1 ≤ start ≤ 1,000 (starting room)Making the pushes one at a time costs up to 10^9 steps. The copies are fewer than twice the pushes, so the total is under 2 × 10^9, and a 32-bit capacity can overflow while it doubles. Use 64-bit integers and count the resizes only.