Add Strings
Table of Contents + β
Add Strings looks easy at first. Just turn the strings into numbers and add them, right? But that is exactly the trap. The interviewer wants you to add them as text, digit by digit. Why? Because real numbers can be longer than any built-in integer can hold. So this question is really about doing addition by hand, the way you learned in school.
π― The Problem
You get two numbers given as strings, and you must return their sum, also as a string.
- The inputs are strings of digits, like
"456"and"77". - Return the sum as a string too.
- You cannot convert the whole string to an integer in one shot. You add them yourself.
- The numbers can be very long, longer than any built-in
intorlong.
Think about how you add on paper. You line the numbers up on the right. Then you add the last digits first. If the sum is ten or more, you keep a carry for the next column. The carry is the extra one you push to the next column when two digits add up past nine.
Input: num1 = "456", num2 = "77"Output: "533"
Explanation: 4 5 6+ 7 7------- 5 3 3 (6+7=13 write 3 carry 1, 5+7+1=13 write 3 carry 1, 4+1=5)Here is the addition lined up the way you would write it on paper, with the carry moving left.
π’ Approach 1: Convert To Numbers (Brute Force)
Call something like int(num1) + int(num2) and turn the result back into a string.
The idea:
- Parse each whole string into an integer.
- Add the two integers.
- Turn the sum back into a string.
Why it is weak:
- It breaks the moment a number is bigger than the languageβs integer can hold.
- In C, C++ and Java the value overflows and you get a garbage answer. Overflow means the number got too big for its box, so it wraps around to a wrong value.
- Python would not overflow, but the interviewer is testing the manual method on purpose.
- So this idea misses the point of the question.
Here is the conversion code for that idea:
def add_strings(num1, num2): return str(int(num1) + int(num2))β‘ Approach 2: Add Digit By Digit With A Carry (Best)
The idea in one line: add the two strings the way you do on paper, from the right, carrying when a column passes nine.
The idea:
- A pointer is just an index saying which digit you are looking at.
- Use two pointers, one per string. Both start at the last digit and move left.
How it works:
- Add the two current digits plus any carry from before.
- The last digit of that sum is the digit you write.
- The carry for the next column is the sum divided by ten.
- When one string runs out, treat its missing digit as zero.
- Keep going until both strings are done and there is no carry left.
- Build the answer from right to left, then reverse once at the end.
Why it is safe:
- It never converts the whole number, so it never overflows.
- It handles numbers of any length.
- It touches each digit exactly once.
Steps to Solve
- Set one pointer at the last character of
num1and another at the last character ofnum2. - Start the carry at zero.
- While either pointer is still valid or the carry is not zero, do the next steps.
- Read the current digit from each string, or use zero if that pointer ran past the start.
- Add both digits and the carry. The written digit is the sum modulo ten. The new carry is the sum divided by ten.
- Append the written digit, move both pointers left, and repeat.
- Reverse the collected digits to get the final string.
Here is the loop in action on "456" and "77". Watch the carry move left at each step until both strings and the carry are done.
This Python version collects digits in a list, then joins them in reverse order.
def add_strings(num1, num2): i = len(num1) - 1 # last digit of num1 j = len(num2) - 1 # last digit of num2 carry = 0 result = []
while i >= 0 or j >= 0 or carry > 0: d1 = int(num1[i]) if i >= 0 else 0 # 0 if num1 ran out d2 = int(num2[j]) if j >= 0 else 0 # 0 if num2 ran out total = d1 + d2 + carry result.append(str(total % 10)) # write last digit carry = total // 10 # keep the carry i -= 1 j -= 1
return "".join(reversed(result)) # we built it backwards
print(add_strings("456", "77"))The output of the above code will be:
533Let us walk through the Python version line by line. The two pointers i and j start at the last index of each string. We add from the right, so the last character is where the math begins. The carry starts at zero because nothing has overflowed yet.
The while loop keeps running while either pointer is still valid or the carry is not zero. That last part matters. If the final addition makes a carry, like "5" + "5" giving "10", the loop runs one extra time to write that leading 1.
Inside, d1 = int(num1[i]) if i >= 0 else 0 reads the current digit. But if that pointer already went past the start, we use 0 instead. This is how we handle two strings of different lengths without padding them by hand.
Then total = d1 + d2 + carry is the column sum. total % 10 is the last digit of that sum, which is the digit we keep. carry = total // 10 is the part that moves left. For 13, the modulo gives 3 and the floor division gives 1. We append the digit and step both pointers left. At the end we reverse, because we built the answer from right to left.
β±οΈ Time and Space Complexity
We touch each digit of each string exactly once. So the time is O(max(m, n)), where m and n are the lengths of the two strings. We need space to hold the answer, which is also about the length of the longer string. So the space is O(max(m, n)) too. There is no faster way, because you must look at every digit at least once to add it.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Convert to int and add | O(max(m, n)) | O(max(m, n)) |
| Digit by digit with carry | O(max(m, n)) | O(max(m, n)) |
Tip
The trick most people forget is the final carry. After both strings are done, you might still have a carry of one. Keep the loop running while the carry is not zero, or you will drop a leading digit.
π§© Key Takeaways
- β Add the strings the way you do on paper, from the rightmost digit to the left.
- β Keep a carry. The written digit is the sum modulo ten, and the carry is the sum divided by ten.
- β When one string is shorter, treat its missing digits as zero.
- β Keep looping while the carry is not zero, so you never drop the final leading digit.
- β Converting to a number can overflow in C, C++, and Java, which is why the manual method is the safe answer.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Why does the interviewer ask you to add the strings digit by digit instead of converting to numbers?
Why: Very long numbers overflow built-in integer types, so adding digit by digit is the safe, general method.
- 2
When adding a single column, how do you get the digit to write and the carry?
Why: The written digit is sum % 10 and the carry passed left is sum // 10.
- 3
What do you use for a digit when one string is shorter and its pointer ran past the start?
Why: A missing digit counts as zero, just like leading blanks in paper addition.
- 4
Why must the loop keep running while the carry is not zero?
Why: A final carry, like in 5 + 5 = 10, adds a new leading digit, so the loop runs one extra time.