Engineering platform~12 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-217hashing
An API gateway receives the calls of every service in an app. Each request carries a request id. A client that sends the same id twice is replaying a request, and the gateway treats the second copy as a replay.
Security wants to start a review at the first replay in a day's log. The log lists the request ids in the order the requests arrived.
Write first_replayed(ids).
ids[i] is the request id of the i-th request.i such that ids[i] equals some ids[k] with k < i.Input: ids = [31, 8, 54, 8, 31, 77]
Output: 3The trace keeps a set of the ids read so far.
| Position | id | In the set? | Set after |
|---|---|---|---|
| 0 | 31 | no | 31 |
| 1 | 8 | no | 31, 8 |
| 2 | 54 | no | 31, 8, 54 |
| 3 | 8 | yes: a replay | stop |
The id 31 repeats later, at position 4, but the replay at position 3 comes first.
Input: ids = [4, 9, 16, 25]
Output: -1Every id is different, so there is no replay.
Input: ids = [7, 7]
Output: 1The second request repeats the first, so the replay is at position 1.
1 ≤ ids.length ≤ 100,000 (requests in a log)0 ≤ ids[i] ≤ 10^9 (request ids)Comparing each id with all the ids before it costs about n × n / 2 checks. At n = 100,000 that is about 5 × 10^9, far over the budget of about 10^8 simple operations a second. A hash set answers "seen before?" in one step on average, so one pass makes about n steps.
Read the values too. An id is at most 10^9, which fits in a 32-bit int.