Payments app~20 min2s · 256 MBtarget O(n) time, O(n) spacequeues · hashing
A payments app keeps one log of events: payments made by customers and refunds sent back to them. Finance must link every refund to the payment it returns.
The rule is first in, first out. A refund goes to the oldest payment of the same customer and the same amount that no earlier refund has taken. A refund with no such payment is flagged for review.
Write match_refunds(kinds, customers, amounts).
i is a payment when kinds[i] == 0 and a refund when kinds[i] == 1. It belongs to customer customers[i] and moves amounts[i] units.-1 when there is none.Input: kinds = [0, 0, 1, 0, 1, 1, 1], customers = [4, 4, 4, 9, 4, 9, 9], amounts = [250, 250, 250, 800, 250, 800, 800]
Output: [0, 1, 3, -1]The trace keeps a queue of unmatched payment indexes for each customer and amount.
| i | Event | Key | Queue before | Result |
|---|---|---|---|---|
| 0 | payment | (4, 250) | empty | queue (4, 250): 0 |
| 1 | payment | (4, 250) | 0 | queue (4, 250): 0, 1 |
| 2 | refund | (4, 250) | 0, 1 | takes 0 |
| 3 | payment | (9, 800) | empty | queue (9, 800): 3 |
| 4 | refund | (4, 250) | 1 | takes 1 |
| 5 | refund | (9, 800) | 3 | takes 3 |
| 6 | refund | (9, 800) | empty | -1 |
The four refunds take payments 0, 1 and 3, and the last one has no payment left. The output is [0, 1, 3, -1].
Input: kinds = [1, 0, 1], customers = [3, 3, 3], amounts = [100, 100, 100]
Output: [-1, 1]The first refund comes before any payment, so it gets -1. The payment at index 1 cannot go back and match it.
Input: kinds = [0, 1], customers = [5, 5], amounts = [100, 200]
Output: [-1]The amounts differ, so the refund has no payment to take.
1 ≤ kinds.length ≤ 100,000 (events in the log); the three lists have the same lengthkinds[i] is 0 or 11 ≤ customers[i] ≤ 1,000,000,000 (customer ids)1 ≤ amounts[i] ≤ 1,000,000,000 (units)Scanning back over the log for every refund costs about n × n / 2 steps, about 5 × 10^9 at n = 100,000. A map from each customer and amount to a queue of waiting payments makes every event one map lookup and one queue step.