Chat app~15 min2s · 256 MBtarget O(k) time, O(1) spacecomplexity
A chat app keeps its members in groups, listed in a fixed order. A safety scan compares members in two ways. Inside each group, it compares every pair of members once. Then it compares every member of a group with every member of the next group in the list.
Each comparison of two members is one check. The team wants the exact number of checks before the scan is scheduled, without running it.
Write count_pair_checks(sizes).
sizes[g] is the number of members in group g.Input: sizes = [3, 2, 4]
Output: 24Each row is one group. Inside, a group of s makes s(s-1)/2 checks. Across, it makes s times the next size.
| Group | Size | Inside checks | Cross checks with the next group | Running total |
|---|---|---|---|---|
| 0 | 3 | 3 | 3 × 2 = 6 | 9 |
| 1 | 2 | 1 | 2 × 4 = 8 | 18 |
| 2 | 4 | 6 | none: it is the last group | 24 |
The total is 24 checks.
Input: sizes = [5]
Output: 10One group of 5 makes 5 × 4 / 2 = 10 checks inside. There is no next group, so nothing crosses.
Input: sizes = [1, 1, 1]
Output: 2A group of one has no inside pair. Only the two cross checks remain: 1 × 1 + 1 × 1 = 2.
0 ≤ sizes.length ≤ 100,000 (groups)1 ≤ sizes[g] ≤ 100,000 (members in one group)Running the loops makes about 10^15 checks in the largest case, so you must count with formulas. A group of s members makes s × (s − 1) / 2 checks inside. The total needs a 64-bit integer.