Payments app~20 min2s · 256 MBtarget O(n) time, O(n) spacequeues
A payments app lists transactions in the order they happen. Each amount is in minor units. A payment is positive, a refund is negative, and 0 is a free action.
A fraud analyst scrolls through windows of k consecutive transactions. For each window, the analyst wants the oldest refund in it: the one closest to the left edge. A list can hold 300,000 amounts and k can be 150,000. Reading every window from its left edge until a refund shows up is too slow when refunds are rare.
Write first_refunds(amounts, k).
amounts[i] is the amount of transaction i. A refund is a negative amount.k consecutive amounts, from the window that starts at position 0 to the window that ends at the last position.len(amounts) - k + 1 values.Input: amounts = [4, -3, 5, 7, -8, 2, 6], k = 3
Output: [-3, -3, -8, -8, -8]Keep a queue of the positions of refunds, oldest first. Before each answer, remove the positions that have left the window. The front of the queue is the answer.
| Window | Amounts | Queue of refund positions | Answer |
|---|---|---|---|
| 0 to 2 | 4, -3, 5 | 1 | -3 |
| 1 to 3 | -3, 5, 7 | 1 | -3 |
| 2 to 4 | 5, 7, -8 | 4 (position 1 left) | -8 |
| 3 to 5 | 7, -8, 2 | 4 | -8 |
| 4 to 6 | -8, 2, 6 | 4 | -8 |
Input: amounts = [10, 20, 30], k = 2
Output: [0, 0]There are no refunds, so every window answers 0.
Input: amounts = [-5, 3, -2, 4], k = 1
Output: [-5, 0, -2, 0]A window of one amount answers with that amount when it is a refund, and 0 otherwise.
1 ≤ length of amounts ≤ 3 × 10^5, and -10^9 ≤ amounts[i] ≤ 10^91 ≤ k ≤ length of amountsScanning each window from its left edge costs up to k steps, and there are n - k + 1 windows. For n = 200,000 and k = 100,000 with refunds only at the far end of each window, that is about 10^10 steps.
A refund enters the queue once and leaves it at most once, so the whole pass costs about 2n queue steps. Answers are amounts, so they fit in a 32-bit int.