Online store~12 min2s · 256 MBtarget O(n) time, O(1) spaceprefix-sums
You work on an online store that sells gift bundles. A bundle holds two items from two different categories, such as one book and one candle. Two items of the same category do not make a bundle.
Your team lead asks: "In how many ways can a customer pick the two items of a bundle?" The store has up to 100,000 categories.
Write ways_to_pick_two(counts).
counts[i] is the number of items in category i. Every item is different from every other item.0 when there is only one category.Input: counts = [2, 3, 4]
Output: 26Read the categories from left to right. Keep seen, the number of items in earlier categories. Each item of the new category pairs with every item already seen.
| Category | Items | seen before | New ways (items × seen) | Total ways |
|---|---|---|---|---|
| 0 | 2 | 0 | 0 | 0 |
| 1 | 3 | 2 | 6 | 6 |
| 2 | 4 | 5 | 20 | 26 |
Input: counts = [5]
Output: 0With one category there is nobody to pair with.
Input: counts = [1, 1, 1, 1]
Output: 6Four categories of one item each: any two of them pair, which is 6 ways.
1 ≤ len(counts) ≤ 100,0001 ≤ counts[i] ≤ 1,000Trying every pair of categories takes n × (n - 1) / 2 steps: 4,999,950,000 for 100,000 categories. That is too slow. A single pass that remembers the number of earlier items fits the limit.