Online store~25 min2s · 256 MBtarget O(total characters) time, O(n + buckets) spacehashing
An online store keeps its orders in a hash table, and every order has a short code such as ab12. To choose a bucket, the table hashes the code. It starts at 0 and, for each character in turn, multiplies by 31, adds the character's number, and keeps the remainder after dividing by the bucket count.
Two different codes that reach the same bucket are a collision. Before a launch, the platform team wants to know how many pairs of different codes collide. A code that appears twice in the list is one order.
Write colliding_pairs(codes, buckets).
codes[i] is an order code of lowercase letters and digits. The same code may appear more than once, and it counts once.h = 0. For each character, set h = (h × 31 + value) mod buckets.value is the ASCII number of the character: a is 97 and 0 is 48.Input: codes = ["ab", "ba", "abc", "b", "ab", "cab", "a1"], buckets = 7
Output: 4The trace keeps a set of codes and a counter for each bucket. Each new code collides with every code already in its bucket.
| Code | Repeat | Bucket | Codes already there | Collisions so far |
|---|---|---|---|---|
| ab | no | 4 | 0 | 0 |
| ba | no | 6 | 0 | 0 |
| abc | no | 6 | 1 (ba) | 1 |
| b | no | 0 | 0 | 1 |
| ab | yes | 1 | ||
| cab | no | 6 | 2 (ba, abc) | 3 |
| a1 | no | 4 | 1 (ab) | 4 |
The pairs are ba with abc, ba with cab, abc with cab, and ab with a1.
Input: codes = ["x", "x", "x"], buckets = 3
Output: 0All three entries are the same code, so there is one order and no pair.
Input: codes = ["a", "b"], buckets = 1
Output: 1With one bucket, every pair collides.
1 ≤ codes.length ≤ 20,000 (orders in one batch)1 ≤ codes[i].length ≤ 12, lowercase letters and digits1 ≤ buckets ≤ 100,000Comparing the buckets of every pair of codes costs about n × n / 2 pairs. That is 2 × 10^8 at n = 20,000, and each pair hashes two codes of up to 12 characters. That is far over the budget of about 10^8 simple operations a second. Hashing each code once and counting a bucket as you go makes about 240,000 steps.
Read the values too. During the hash, h stays below buckets (at most 100,000), so h × 31 + 122 is below 3.2 million and fits in a 32-bit int. The count of pairs can reach 2 × 10^8, so use a 64-bit type to be safe.