Payments app~12 min2s · 256 MBtarget O(n) time, O(1) spacenumber-theory
You work on a payments app. At night it settles waiting payments in pairs. Two payments can share a batch only when their total, in whole units, splits into two equal halves. That means the total is even.
Your team lead asks: "How many different pairs of waiting payments can share a batch?" A busy night can hold 100,000 payments.
Write count_even_pairs(amounts).
amounts[i] is the size of payment i, in whole units.i < j. Pairs are counted by position, so two payments of the same size still make a pair.amounts[i] + amounts[j] is even. Return 0 when there is none.Input: amounts = [3, 5, 8, 2, 7]
Output: 4Only the parity of each amount matters. Even plus even is even, odd plus odd is even, and odd plus even is odd.
| Amount | Odd or even |
|---|---|
| 3 | odd |
| 5 | odd |
| 8 | even |
| 2 | even |
| 7 | odd |
Three payments are odd, so they make 3 pairs: (3, 5), (3, 7) and (5, 7). Two payments are even, so they make 1 pair: (8, 2). That gives 4 pairs.
Input: amounts = [4, 6, 10]
Output: 3All three are even, so every pair works: (4, 6), (4, 10) and (6, 10).
Input: amounts = [1, 2]
Output: 0One odd and one even payment make an odd total, so no pair works.
1 ≤ len(amounts) ≤ 100,0001 ≤ amounts[i] ≤ 1,000,000Checking every pair takes n × (n - 1) / 2 checks: 4,999,950,000 for 100,000 payments. That is too many for a 2-second limit. An answer that needs one pass over the list, or one pass and a little arithmetic, is what the limit asks for.