Practice problem · medium
A payments app settles a batch of transfers. Each amount is signed: money in is positive, and money out is negative. Amounts may repeat.
Reconciliation looks for groups of four amounts that add up to a target, such as the fee of a split payment. Two groups with the same four values count as the same combination, whichever transfers they come from. You are asked to count the distinct combinations of values.
Write count_quads(amounts, target).
amounts is the batch, in no particular order. Amounts may repeat.target.Input: amounts = [1, 0, -1, 0, -2, 2], target = 0
Output: 3Sort the amounts: -2, -1, 0, 0, 1, 2. Fix the first two, then walk two pointers over the rest. Repeated values are skipped, so each combination is counted once.
| First | Second | lo value | hi value | Total | What happens |
|---|---|---|---|---|---|
| -2 | -1 | 0 | 2 | -1 | too low: lo moves up |
| -2 | -1 | 0 | 2 | -1 | the second 0 is still too low: lo moves up |
| -2 | -1 | 1 | 2 | 0 | match: -2, -1, 1, 2. Count is 1 |
| -2 | 0 | 0 | 2 | 0 | match: -2, 0, 0, 2. Count is 2 |
| -1 | 0 | 0 | 2 | 1 | too high: hi moves down |
| -1 | 0 | 0 | 1 | 0 | match: -1, 0, 0, 1. Count is 3 |
The other choices of first and second entries have no match. The answer is 3.
Input: amounts = [2, 2, 2, 2, 2], target = 8
Output: 1Every quadruple has the values 2, 2, 2, 2. They are one combination.
Input: amounts = [1, 2, 3], target = 6
Output: 0A quadruple needs four entries, and there are only three.
1 ≤ amounts.length ≤ 400 (transfers in one batch)-10^6 ≤ amounts[i] ≤ 10^6 (amounts in minor units)-4 × 10^6 ≤ target ≤ 4 × 10^6Checking every set of four positions costs about n^4 ÷ 24 checks. At n = 400 that is 1.1 × 10^9: about 11 seconds at 10^8 operations a second. Fixing two entries and walking two pointers costs about n × n × n ÷ 6 steps, 11 million.
A total of four amounts is at most 4 × 10^6 in size, which fits in a 32-bit integer. So does the count of combinations.
count_quads · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.