Payments app~15 min2s · 256 MBtarget O(n) time, O(n) spacehashing
A payments app sends money between users. Sometimes a user taps "Send" twice, or the phone retries after a slow network. The same transfer then reaches the server two or three times within a few seconds.
The fraud desk wants a count of these repeats in a month of transfers. A repeat has the same sender, the same receiver and the same amount as an earlier transfer, and it arrives soon after it.
Write count_duplicate_transfers(senders, receivers, amounts, times, window).
i goes from user senders[i] to user receivers[i] and moves amounts[i] units. It arrives at second times[i]. The times never go down.i is a duplicate when an earlier transfer has the same sender, receiver and amount. The latest such transfer must have arrived at most window seconds before it: times[i] - latest <= window.Input: senders = [7, 7, 3, 7, 7], receivers = [9, 9, 9, 9, 4], amounts = [500, 500, 500, 500, 500], times = [100, 130, 140, 400, 410], window = 60
Output: 1The trace keeps the latest time for each sender, receiver and amount.
| i | Key (sender, receiver, amount) | Latest earlier time | Gap | Duplicate? |
|---|---|---|---|---|
| 0 | (7, 9, 500) | none | none | no |
| 1 | (7, 9, 500) | 100 | 30 | yes |
| 2 | (3, 9, 500) | none | none | no |
| 3 | (7, 9, 500) | 130 | 270 | no |
| 4 | (7, 4, 500) | none | none | no |
Transfer 1 repeats transfer 0 after 30 seconds, so the output is 1. Transfer 3 has the same key, but 270 seconds have passed.
Input: senders = [1, 1, 1], receivers = [2, 2, 2], amounts = [50, 50, 50], times = [0, 40, 80], window = 40
Output: 2Transfer 2 is 80 seconds after transfer 0, but only 40 seconds after transfer 1, the latest one with its key. So both repeats count, and the output is 2.
Input: senders = [4, 4], receivers = [5, 5], amounts = [300, 301], times = [10, 10], window = 100
Output: 0The amounts differ, so these are two different transfers.
1 ≤ senders.length ≤ 100,000 (transfers in a month); the four lists have the same length1 ≤ senders[i], receivers[i] ≤ 1,000,000,000 (user ids)1 ≤ amounts[i] ≤ 1,000,000,000 (units)0 ≤ times[i] ≤ 2,678,400 (seconds since the start of the month), never going down0 ≤ window ≤ 86,400Comparing every transfer with every earlier one costs about n × n / 2 checks, about 5 × 10^9 at n = 100,000. A map from the key to its latest time answers "seen recently?" in one step, so one pass is enough. The key has three fields of up to 10^9 each, so build it as a tuple or a string, not as one sum.