Home
DSA Patterns
Two Pointers
Add Strings
Add Strings
Add two non-negative numbers given as strings with two pointers from the right and a carry, without converting them to integers.
Problem Understanding
Add Strings: given two non-negative integers num1 and num2 as strings, return their sum as a string. You may not use a big-integer library or convert the inputs to integers directly.
Examples: "11" + "123" = "134", "456" + "77" = "533", and "0" + "0" = "0".
The Intuition: Column Addition, Right to Left
Add the numbers the way you would on paper:
- Point
iandjat the last digit of each string. - A column's total is the carry plus the digits there, at most
1 + 9 + 9 = 19. - The digit to write is
total % 10, and the carry into the next column istotal / 10. - When one string runs out, treat its digits as 0; when both run out, a leftover carry still adds a digit.
It is the two pointers idea run from the ends of two strings at once, exactly Add Binary in base 10. Multiply Strings extends the same carry handling to every digit pair.
Interactive Walkthrough
num1 and num2 are right-aligned above the sum, with the carry shown over the next column. Try Carry chain to watch a carry ripple through every column and add a new digit at the front.
Dry Run Table
Input: num1 = "456", num2 = "77"
| Column | num1 digit | num2 digit | carry in | total | write | carry out |
|---|---|---|---|---|---|---|
| 0 | 6 | 7 | 0 | 13 | 3 | 1 |
| 1 | 5 | 7 | 1 | 13 | 3 | 1 |
| 2 | 4 | — | 1 | 5 | 5 | 0 |
Answer: written right to left 3, 3, 5, reversed: "533".
The Solution Template
One loop that runs while either string has digits or a carry is left. Digits are converted one character at a time. C fills a buffer from the end and then shifts the answer to the front so the returned pointer can be freed.
Add Strings Code
1var addStrings = function(num1, num2) {2 let i = num1.length - 1, j = num2.length - 1, carry = 0;3 const out = [];4 while (i >= 0 || j >= 0 || carry) {5 let total = carry;6 if (i >= 0) total += num1.charCodeAt(i--) - 48;7 if (j >= 0) total += num2.charCodeAt(j--) - 48;8 out.push(total % 10);9 carry = Math.floor(total / 10);10 }11 return out.reverse().join('');12};
Edge Cases & Common Mistakes
- Final carry:
"999" + "1"is"1000"; keep looping while the carry is not 0. - Different lengths: once a string is used up, add only the other digit and the carry.
- Both zero:
"0" + "0"is"0". - Converting the whole string:
int(num1)is not allowed, and overflows in fixed-width languages for long inputs. - Prepending each digit: O(n²) on immutable strings; append, then reverse once.
Summary
Walk both strings from the right with a carry. Each column writes total % 10 and carries total / 10; keep going while either string has digits or the carry is not 0. Reverse the written digits. O(max(m, n)) time and space.
More practice: DSA interview questions with answers · patterns cheat sheet
