Bank app~30 min2s · 256 MBtarget O(n) time, O(k) spaceclassic twin: lc-220hashing · sorting
A bank's fraud check looks at a stream of account entries. Each entry is a signed amount in minor units, and credits are negative. The check flags two different entries that are at most k places apart in the stream and whose amounts differ by at most t. The stream can hold 100,000 entries, so the check must be fast.
Write has_near_duplicate(amounts, k, t).
amounts is the list of signed amounts, in stream order.true when there are two places i and j, with i != j and |i - j| <= k, such that |amounts[i] - amounts[j]| <= t.false.Input: amounts = [50, 20, 71, 45], k = 3, t = 5
Output: truePut each amount in a bucket of width t + 1 = 6. A match is in the same bucket, or in a neighbouring bucket within t. Keep only the last k amounts.
The bucket width is t + 1 = 6.
| Place | Amount | Bucket | Buckets held before | Match? |
|---|---|---|---|---|
| 0 | 50 | 8 | {} | no |
| 1 | 20 | 3 | {8: 50} | no |
| 2 | 71 | 11 | {3: 20, 8: 50} | no |
| 3 | 45 | 7 | {3: 20, 8: 50, 11: 71} | yes: 50 in the bucket above, gap 5 |
The answer is true.
Input: amounts = [10, 50, 12], k = 1, t = 5
Output: falseThe amounts 10 and 12 are close in value, but they are 2 places apart and k is 1. The answer is false.
Input: amounts = [-4, 3], k = 1, t = 7
Output: trueNegative amounts count too: the difference is 7, which is within t. The answer is true.
0 ≤ amounts.length ≤ 100,000 (entries)-1,000,000,000 ≤ amounts[i] ≤ 1,000,000,000 (minor units)0 ≤ k ≤ 100,000 and 0 ≤ t ≤ 1,000,000,000Comparing each entry with the k entries after it costs about n × k, which is 10^10 when k is as large as n. Bucketing makes each entry cost a constant number of steps.