visual walkthrough
Add Two Numbers
Digit-by-digit addition with a carry; very frequently asked.
The idea
The digits are stored smallest first, which is exactly the order you add in on paper: ones, then tens, then hundreds.
Add the two digits plus the carry, write the last digit of the total, carry the rest. Keep going while either list or the carry has something left.
Complexity
| approach | time | space |
|---|---|---|
| Read as whole numbers | O(n + m) | O(n + m) |
| Digit by digit with a carry | O(max(n, m)) | O(1) extra |