Payments app~20 min2s · 256 MBtarget O(n) time, O(n) spacecomplexity
A payments service replays a day of transaction ids to catch retries. Its filter keeps a plain list of the ids it has seen. For each id it asks whether the id is already in the list, and adds it when it is not.
The code has one visible loop, so the team counted one step per id. The real work hides in the membership test. You will count it exactly.
Write count_hidden_comparisons(ids).
The filter runs this code. The test x in seen on a list compares x with the items of seen from the front, one at a time, and stops at the first equal item.
def filter_retries(ids):
seen = []
for x in ids:
if x in seen: # a hidden loop: one comparison per item it looks at
continue
seen.append(x)Input: ids = [3, 8, 3, 5, 8]
Output: 6Each row is one membership test.
| Id | Seen before the test | Comparisons | Found? |
|---|---|---|---|
| 3 | [] | 0 | no: added |
| 8 | [3] | 1 | no: added |
| 3 | [3, 8] | 1 | yes, at the front |
| 5 | [3, 8] | 2 | no: added |
| 8 | [3, 8, 5] | 2 | yes, second |
The total is 0 + 1 + 1 + 2 + 2 = 6 comparisons, for 5 ids.
Input: ids = [7, 7, 7, 7]
Output: 3The list holds only 7. Every test after the first finds it at the front: 0 + 1 + 1 + 1 = 3.
Input: ids = [1, 2, 3, 4]
Output: 6No id repeats, so every test scans the whole list: 0 + 1 + 2 + 3 = 6.
0 ≤ ids.length ≤ 100,000 (transactions in the replay)1 ≤ ids[i] ≤ 1,000,000 (transaction ids)With no repeat, the tests make n(n-1)/2 comparisons, which is 4,999,950,000 at n = 100,000. Running the filter is too slow, and the total passes 2 × 10^9, so it needs a 64-bit integer.