Bank app~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-2linked-lists
A bank app's reporting tool adds up exact totals that are too large for any whole-number field. It stores each total as a chain of decimal digits, with the lowest digit first, one digit in each node.
To add two totals, the tool walks both chains together, like adding by hand on paper. The chains can have different lengths, and each can hold up to 100,000 digits.
Write add_chains(first, second).
first and second are the first nodes of two non-empty chains. Each node's val is one digit, 0 to 9, and the lowest digit comes first.The tests give each chain as the list of its digits from the head, and read your answer the same way.
Input: first = [6, 1, 5], second = [7, 8]
Output: [3, 0, 6]The chains are 516 and 87, and 516 + 87 = 603.
| Step | first | second | carry in | total | digit written | carry out |
|---|---|---|---|---|---|---|
| [1] | 6 | 7 | 0 | |||
| [3] | 6 | 7 | 0 | 13 | 3 | 1 |
| [3] | 1 | 8 | 1 | 10 | 0 | 1 |
| [3] | 5 | null | 1 | 6 | 6 | 0 |
Input: first = [9, 9, 9, 9], second = [1]
Output: [0, 0, 0, 0, 1]The numbers are 9,999 and 1. The carry travels to the end and adds a fifth digit.
Input: first = [0], second = [0]
Output: [0]The sum of 0 and 0 is the single digit 0.
1 ≤ number of nodes in each chain ≤ 10^50 ≤ node.val ≤ 9A number with 10^5 digits does not fit in any machine integer, so the digits must be added one at a time.
Reading digit number i of each chain by walking from its head costs i hops. Doing that for every i is about n² / 2 hops for each chain: 10^10 hops at this size. Walking both chains once costs 10^5 hops.