Online store~15 min2s · 256 MBtarget O(n) time, O(n) spacecomplexity
An online store receives its orders as a nightly file of order codes. A clean-up scan looks for repeated codes. It takes each position in turn. It checks the codes after it, one at a time, and stops its scan the moment it finds a copy.
Capacity planning wants to know how much work the scan does. Each comparison of two codes is one check. You will report the exact number of checks without running the slow scan.
Write count_checks(codes).
codes[i] is the order code at position i.i from 0 to n - 1, and for each i it takes each j from i + 1 to n - 1.j it makes one check of codes[j] against codes[i]. It leaves the inner loop at once when they are equal.Input: codes = [4, 7, 4, 9]
Output: 5Each row is the scan from one position. The scan counts every check, including the one that finds the copy.
| Position i | Code | Checks made | Why it stops |
|---|---|---|---|
| 0 | 4 | 2 | finds a 4 at position 2 |
| 1 | 7 | 2 | no 7 after it: runs to the end |
| 2 | 4 | 1 | no 4 after it: runs to the end |
| 3 | 9 | 0 | nothing after it |
The total is 2 + 2 + 1 + 0 = 5 checks.
Input: codes = [3, 8, 1]
Output: 3No code repeats, so every scan runs to the end: 2 + 1 + 0 = 3 checks.
Input: codes = [6, 6, 6, 6]
Output: 3Every scan finds a copy at its first check: 1 + 1 + 1 + 0 = 3 checks.
0 ≤ codes.length ≤ 100,000 (orders in the file)1 ≤ codes[i] ≤ 10,000,000 (order codes)Running the scan can take n × (n − 1) / 2 checks, which is about 5 × 10^9 at n = 100,000. That is too slow, so find the answer by counting where each scan stops. The total also passes 2 × 10^9, so it needs a 64-bit integer.