Bank app~20 min2s · 256 MBtarget O(n log n + m log m) time, O(n + m) spacemerge-sorted · two-pointers · sorting
A bank app keeps two accounts for each business customer: an operating account and a reserve account. Every night the ledger saves a balance snapshot of each account. The snapshots are saved as they are produced, so they are in no order.
An auditor wants to know how close the two accounts ever came to each other. The auditor picks one snapshot of the operating account and one snapshot of the reserve account, and looks at the gap between them. The smallest gap there is, is the answer.
Write smallest_gap(first, second).
first[i] is a balance snapshot of the operating account, in minor units (cents). second[j] is a snapshot of the reserve account. Neither list is in order, and balances may repeat.Input: first = [5200, -1300, 9100, 2600], second = [7400, 300, 11800, 4100]
Output: 1100Sorted, the lists are [-1300, 2600, 5200, 9100] and [300, 4100, 7400, 11800]. The trace works on those sorted copies. best starts at the gap of the two lowest balances, 1600.
| i | j | first[i] | second[j] | Gap | best after | Move |
|---|---|---|---|---|---|---|
| 0 | 0 | -1300 | 300 | 1600 | 1600 | the first is lower: i becomes 1 |
| 1 | 0 | 2600 | 300 | 2300 | 1600 | the second is lower: j becomes 1 |
| 1 | 1 | 2600 | 4100 | 1500 | 1500 | the first is lower: i becomes 2 |
| 2 | 1 | 5200 | 4100 | 1100 | 1100 | the second is lower: j becomes 2 |
| 2 | 2 | 5200 | 7400 | 2200 | 1100 | the first is lower: i becomes 3 |
| 3 | 2 | 9100 | 7400 | 1700 | 1100 | the second is lower: j becomes 3 |
| 3 | 3 | 9100 | 11800 | 2700 | 1100 | the first is lower: i becomes 4, the walk ends |
The balances 5200 and 4100 are only 1100 apart.
Input: first = [-2500, 800, 3100], second = [6000, 3100]
Output: 0Both accounts once held 3100. A gap of 0 cannot be beaten, so the walk stops there.
Input: first = [-1000000000000], second = [1000000000000]
Output: 2000000000000There is one pair. Its gap is 2 × 10^12, which does not fit in a 32-bit integer.
1 ≤ first.length ≤ 100,000 (nightly snapshots of one account)1 ≤ second.length ≤ 100,000-10^12 ≤ first[i], second[j] ≤ 10^12 (balances in minor units)Comparing every snapshot of one account with every snapshot of the other costs n × m comparisons. At n = m = 100,000 that is 10^10: about 100 seconds at 10^8 operations a second, against a limit of 2 seconds. A solution that sorts both lists and then walks them once costs about 3.4 × 10^6 operations, which fits easily.
Read the values too. A balance can reach 10^12 either way, so a gap can reach 2 × 10^12. That is beyond a 32-bit integer, so use a 64-bit type (long in Java, long long in C++).