Payments app~20 min2s · 256 MBtarget O(n) time, O(n) spaceread-write-pointers · two-pointers · hashing
A payments app receives payment requests in batches. Each request carries an idempotency key, a large number that the client picks once per payment. When a client gets no reply in time, it sends the same request again, with the same key.
The gateway must charge each payment once. So before it processes a batch, it keeps only the first request for each key and drops every retry. The kept requests stay in arrival order. A batch can hold up to 100,000 requests, and the gateway edits the batch buffer in place instead of building a second one.
Write first_uses(keys).
keys[i] is the idempotency key of the request at position i of the batch, in arrival order.keys in place, then return the kept prefix. The judge checks only the list you return.Input: keys = [204, 517, 204, 830, 517, 291]
Output: [204, 517, 830, 291]| read | Key | Seen before? | Action | write after | Kept prefix |
|---|---|---|---|---|---|
| 0 | 204 | no | kept: copied to position 0 | 1 | 204 |
| 1 | 517 | no | kept: copied to position 1 | 2 | 204, 517 |
| 2 | 204 | yes | retry: skipped | 2 | 204, 517 |
| 3 | 830 | no | kept: copied to position 2 | 3 | 204, 517, 830 |
| 4 | 517 | yes | retry: skipped | 3 | 204, 517, 830 |
| 5 | 291 | no | kept: copied to position 3 | 4 | 204, 517, 830, 291 |
After the pass the buffer holds [204, 517, 830, 291, 517, 291]. Only the first 4 positions are the answer.
Input: keys = [66, 66, 66]
Output: [66]One payment, sent once and retried twice. Only the first request stays.
Input: keys = [9, 1000000000, 4]
Output: [9, 1000000000, 4]No key repeats, so the batch is unchanged.
1 ≤ keys.length ≤ 10^51 ≤ keys[i] ≤ 10^9Checking each request against every kept request is O(n^2). When no key repeats, that is 4,999,950,000 comparisons at n = 10^5, about 50 seconds. Aim for O(n).
The keys go up to 10^9, so an array indexed by key is far too large. A hash set answers "have I seen this key?" in O(1) on average.