Bank app~25 min2s · 256 MBtarget O(n + m) time, O(1) spacemerge-sorted · two-pointers
A bank sends a daily statement, and the finance team keeps its own books. Each entry in either list has a transaction id and an amount in units. Both lists are sorted by id.
At the end of the day, the team reconciles them. It needs every id that is missing from one list, or present in both with different amounts.
Write reconcile(bank_ids, bank_amounts, books_ids, books_amounts).
i of the bank statement has id bank_ids[i] and amount bank_amounts[i]. The books have the same shape in books_ids and books_amounts. Each list has strictly increasing ids.1 if it is only in the bank statement. Report it as kind 2 if it is only in the books.3 if it is in both with different amounts. An id in both with the same amount is not reported.[id, kind], in increasing order of id.Input: bank_ids = [101, 102, 104, 107, 110], bank_amounts = [500, -200, 300, -50, 900], books_ids = [101, 103, 104, 107, 111, 112], books_amounts = [500, 40, 350, -50, 10, 20]
Output: [[102, 1], [103, 2], [104, 3], [110, 1], [111, 2], [112, 2]]The trace keeps one pointer in each list and compares the ids they point to.
| Step | Bank id | Books id | Compare | Result |
|---|---|---|---|---|
| 0 | 101 | 101 | same id | amounts agree: nothing to record |
| 1 | 102 | 103 | bank id is smaller | only in the bank: record (102, 1) |
| 2 | 104 | 103 | books id is smaller | only in the books: record (103, 2) |
| 3 | 104 | 104 | same id | amounts differ: record (104, 3) |
| 4 | 107 | 107 | same id | amounts agree: nothing to record |
| 5 | 110 | 111 | bank id is smaller | only in the bank: record (110, 1) |
| 6 | end | 111 | bank is used up | only in the books: record (111, 2) |
| 7 | end | 112 | bank is used up | only in the books: record (112, 2) |
Ids 101 and 107 agree in both lists. Id 104 is in both with different amounts, so it is reported as 3. The other four ids are each in only one list.
Input: bank_ids = [10, 20], bank_amounts = [5, 6], books_ids = [10, 20], books_amounts = [5, 6]
Output: []Both lists hold the same ids with the same amounts, so nothing is reported. The output is an empty list.
Input: bank_ids = [1, 2, 3], bank_amounts = [10, 20, 30], books_ids = [9], books_amounts = [90]
Output: [[1, 1], [2, 1], [3, 1], [9, 2]]Id 9 is larger than every id in the bank statement. So ids 1, 2 and 3 are only in the bank, and id 9 is only in the books.
1 ≤ bank_ids.length, books_ids.length ≤ 100,000; each amount list has the length of its id list1 ≤ ids ≤ 1,000,000,000, strictly increasing in each list-1,000,000,000 ≤ amounts ≤ 1,000,000,000 (units)Looking up every id of one list in the other list costs about n × m comparisons, up to 10^10. Both lists are already sorted, so one pass with a pointer in each list sees every id in order, about n + m steps. The output can hold up to n + m rows.