Bank app~25 min2s · 256 MBtarget O(n^2) time, O(n^2) spaceclassic twin: lc-454hashing
A bank app closes each day with four internal ledgers. Every ledger lists signed entries in minor units: credits are positive and debits are negative.
An audit looks for sets of four entries, one from each ledger, that net to exactly zero. Two sets are different when they use a different position in at least one ledger. The audit needs the number of such sets.
Write count_balanced_quads(first, second, third, fourth).
i in first, j in second, k in third and l in fourth.first[i] + second[j] + third[k] + fourth[l] == 0.Input: first = [3, -2, 5], second = [1, -4], third = [-4, 2], fourth = [0, -1, 3]
Output: 4Count the totals of the first two ledgers, then look up the negative of each total from the last two.
Totals of first[i] + second[j]: 4 once, -1 twice, -6 once, 6 once, 1 once.
| third + fourth | Total | Partner total needed | Sets found |
|---|---|---|---|
| -4 + 0 | -4 | 4 | 1 |
| -4 + -1 | -5 | 5 | 0 |
| -4 + 3 | -1 | 1 | 1 |
| 2 + 0 | 2 | -2 | 0 |
| 2 + -1 | 1 | -1 | 2 |
| 2 + 3 | 5 | -5 | 0 |
The total is 1 + 0 + 1 + 0 + 2 + 0 = 4.
Input: first = [1], second = [2], third = [3], fourth = [4]
Output: 0The only set sums to 10.
Input: first = [0, 0], second = [0], third = [0, 0], fourth = [0]
Output: 4Every entry is zero, so every set balances: 2 × 1 × 2 × 1 = 4.
1 ≤ the length of each ledger ≤ 500-10^6 ≤ each entry ≤ 10^6 (minor units)Trying every set costs 500 × 500 × 500 × 500 = 6.25 × 10^10 checks, far over the budget of about 10^8 simple operations a second. But 500 × 500 = 250,000, which is small. Splitting the four ledgers into two pairs turns 6.25 × 10^10 into about 500,000 steps.
The answer can reach 6.25 × 10^10, so it needs a 64-bit long. Each entry is at most 10^6 in size, so a total of two entries fits easily in a 32-bit int.