Parcel-delivery app~12 min2s · 256 MBtarget O(n) time, O(n) spacetraversal · hashing
A parcel-delivery app audits one hub. The hub scanner reads the id of every parcel that passes a belt, and a parcel that is scanned twice appears twice in the list. The audit compares one checksum with the hub: the total of the ids, counting each parcel once.
The ids are large, up to 1,000,000,000, and a busy day has up to 100,000 scans. Your first attempt keeps a list of the ids already added and looks in it for each new id.
Write total_of_ids(ids).
ids[i] is the id read by scan i. The same id can appear many times.Input: ids = [7, 3, 7, 5, 3]
Output: 15| Scan | Id | Seen before? | Total after |
|---|---|---|---|
| 0 | 7 | no | 7 |
| 1 | 3 | no | 10 |
| 2 | 7 | yes | 10 |
| 3 | 5 | no | 15 |
| 4 | 3 | yes | 15 |
The different ids are 7, 3 and 5. Their total is 15.
Input: ids = [1000000000, 999999999, 999999998]
Output: 2999999997The three ids are different. The total is above 2,147,483,647, the largest 32-bit integer.
Input: ids = [4, 4, 4]
Output: 4Only one id is different, so the total is 4.
1 ≤ ids.length ≤ 100,000 (scans in one day)1 ≤ ids[i] ≤ 1,000,000,000 (parcel ids)A list lookup costs up to n steps, and you make one for each scan: about 5 × 10^9 steps at n = 100,000. That is too slow. Use a structure that answers "seen before?" in one step. The total can reach 10^14, so it needs a 64-bit integer.