Add Strings (LeetCode 415): Solution and Explanation
Given two non-negative integers as decimal strings, return their sum as a string without converting the whole inputs to integers or using a big-integer library.
Intuition
This is the addition you learned on paper. Line the numbers up on the right, add one column at a time, write the ones digit of that column's total and carry the tens digit into the next column.
A column never needs more than two digits and a carry, so the largest column total is 9 + 9 + 1 = 19 and the carry is always 0 or 1. That is why the inputs can be thousands of digits long without overflowing anything.
The two strings can have different lengths. Instead of padding them, treat a pointer that has moved past the start of its string as contributing a 0, and keep looping while either pointer is still valid or a carry is left over.
Approach: Two pointers from the right with a carry
- Set
i = len(num1) - 1,j = len(num2) - 1andcarry = 0. - While
i >= 0orj >= 0orcarryis non-zero, readd1(or 0 ifi < 0) andd2(or 0 ifj < 0). - Compute
total = d1 + d2 + carry, appendtotal % 10to the result and setcarry = total // 10. - Move both pointers one place left.
- The digits were produced ones-first, so reverse the result before joining it into a string.
Step-by-step example
num1 = "456", num2 = "77"
- Ones column: 6 + 7 + 0 = 13. Write 3, carry 1.
- Tens column: 5 + 7 + 1 = 13. Write 3, carry 1.
- Hundreds column: num2 has run out, so d2 = 0. 4 + 0 + 1 = 5. Write 5, carry 0.
- Both pointers are past the start and carry is 0, so the loop stops with digits [3, 3, 5].
- Reverse to get "533".
Code: Python, Java, C++
1class Solution:
2 def addStrings(self, num1: str, num2: str) -> str:
3 i, j = len(num1) - 1, len(num2) - 1
4 carry = 0
5 result = []
6 while i >= 0 or j >= 0 or carry:
7 d1 = ord(num1[i]) - ord("0") if i >= 0 else 0
8 d2 = ord(num2[j]) - ord("0") if j >= 0 else 0
9 total = d1 + d2 + carry
10 result.append(str(total % 10))
11 carry = total // 10
12 i -= 1
13 j -= 1
14 return "".join(reversed(result))1class Solution {
2 public String addStrings(String num1, String num2) {
3 int i = num1.length() - 1, j = num2.length() - 1;
4 int carry = 0;
5 StringBuilder sb = new StringBuilder();
6 while (i >= 0 || j >= 0 || carry != 0) {
7 int d1 = i >= 0 ? num1.charAt(i) - '0' : 0;
8 int d2 = j >= 0 ? num2.charAt(j) - '0' : 0;
9 int total = d1 + d2 + carry;
10 sb.append(total % 10);
11 carry = total / 10;
12 i--;
13 j--;
14 }
15 return sb.reverse().toString();
16 }
17}1class Solution {
2public:
3 string addStrings(string num1, string num2) {
4 int i = num1.size() - 1, j = num2.size() - 1;
5 int carry = 0;
6 string result;
7 while (i >= 0 || j >= 0 || carry) {
8 int d1 = i >= 0 ? num1[i] - '0' : 0;
9 int d2 = j >= 0 ? num2[j] - '0' : 0;
10 int total = d1 + d2 + carry;
11 result.push_back('0' + total % 10);
12 carry = total / 10;
13 i--;
14 j--;
15 }
16 reverse(result.begin(), result.end());
17 return result;
18 }
19};Time and space complexity
O(max(m, n))
Each column is visited once, and there are at most max(m, n) + 1 columns.
O(max(m, n))
The result holds at most max(m, n) + 1 digits; apart from that only two pointers and a carry are kept.
Other approaches
Pad to equal length (time O(max(m, n)), space O(max(m, n)))
Left-pad the shorter string with zeros so both have the same length, then walk a single index from the right. It removes the bounds checks at the cost of building a padded copy.
Built-in big integers (time O(max(m, n)), space O(max(m, n)))
Python's int or Java's BigInteger would add the numbers in one line, but the problem forbids it, and an interviewer is asking for the carry logic itself.
Common mistakes
- Stopping the loop when both strings are used up and dropping the last carry, so "999" + "1" comes out as "000" instead of "1000".
- Prepending each digit to a string inside the loop. In most languages that copies the string every time and turns the loop quadratic; append and reverse once at the end instead.
- Converting a character to its digit with
int(c)is fine, but in Java, C++ and C# remember to subtract '0' rather than casting the character's code directly.
Frequently asked questions
Can the carry ever be larger than 1?
No. The biggest possible column is 9 + 9 + 1 = 19, so the carry is always 0 or 1.
Why not convert both strings to integers and add them?
The inputs can be up to 10,000 digits, far beyond 64-bit integers, and the problem explicitly forbids big-integer libraries. Column addition works for any length.
How does this relate to Add Two Numbers and Multiply Strings?
Add Two Numbers is the same column addition over linked lists that store digits in reverse. Multiply Strings builds on it: each pair of digits contributes to one column, and carries are propagated the same way.