Payments app~35 min2s · 256 MBtarget O(n^2 log n) time, O(n^2) spaceclassic twin: lc-454, lc-18k-sum · two-pointers · sorting
A payments app settles card, wallet, bank and voucher payments in four separate batches. Each batch is a list of adjustments in minor units. A charge is positive, and a refund is negative.
When the totals do not agree, an analyst looks for adjustments that cancel out. The analyst takes one adjustment from each of the four batches and adds them up. A payments engineer wants to know how many such choices net to exactly zero.
Write count_zero_nets(batch_a, batch_b, batch_c, batch_d).
Input: batch_a = [-200, -900], batch_b = [-300, 400], batch_c = [200, 500], batch_d = [300, 700]
Output: 3Add every amount of A to every amount of B, and every amount of C to every amount of D. Sorted, the pair totals are left = [-1200, -500, -500, 200] and right = [500, 800, 900, 1200]. The walk starts at the lowest left total and the highest right total.
| i | j | left[i] | right[j] | Net | Move | count after |
|---|---|---|---|---|---|---|
| 0 | 3 | -1200 | 1200 | 0 | one left and one right total: add 1 × 1, both pointers pass their runs | 1 |
| 1 | 2 | -500 | 900 | 400 | above zero: j becomes 1 | 1 |
| 1 | 1 | -500 | 800 | 300 | above zero: j becomes 0 | 1 |
| 1 | 0 | -500 | 500 | 0 | two left totals equal -500 and one right total: add 2 × 1, both pointers pass their runs | 3 |
The walk ends with 3 ways.
Input: batch_a = [0, 0], batch_b = [0], batch_c = [0], batch_d = [0, 0]
Output: 4Every amount is zero, so every choice nets zero. There are 2 × 1 × 1 × 2 = 4 choices.
Input: batch_a = [1000000000], batch_b = [1000000000], batch_c = [-1000000000], batch_d = [-1000000000]
Output: 1The pair totals are 2 × 10^9 and -2 × 10^9. Each fits in a 32-bit integer, but a sum of two pair totals may not.
1 ≤ batch_a.length, batch_b.length, batch_c.length, batch_d.length ≤ 800 (adjustments in one settlement batch)-10^9 ≤ batch[i] ≤ 10^9 (adjustments in minor units)Trying one amount from each batch costs n^4 checks. At n = 800 that is about 4.1 × 10^11, far over the budget of about 10^8 simple operations a second. Two pair lists of n^2 = 640,000 totals each fit in memory, and sorting them costs about 1.3 × 10^7 comparisons. The walk then makes at most 1.28 million steps.
Read the values too. A pair total reaches 2 × 10^9, and the sum of two pair totals reaches 4 × 10^9, which does not fit in a 32-bit integer. The number of ways reaches 800^4, which does not fit either. Use a 64-bit type for both.