15% off all plans & roadmaps Use code

See plans

Add Strings

Updated

TL;DR: You add two numbers written as strings by walking both from the right and carrying overflow, the way you add on paper. One pass over the digits gives the answer in linear time without converting either string to a number.

Problem

You receive two strings, num1 and num2. Each one encodes a non-negative integer in base 10. Return a string that encodes the sum of those two integers.

Example 1

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3

Input: num1 = "0", num2 = "0"
Output: "0"

Constraints

  • Each string has between 1 and 10^4 characters.
  • Each string contains only digit characters.
  • A string never starts with a zero unless the whole string is "0".

Constraints that matter

  • Lengths up to 10^4 rule out converting either string to a built-in integer, since 10^4 digits far exceed 64 bits.
  • Lengths up to 10^4 also mean the solution must run in time proportional to the input length, so an O(n^2) scan is too slow.
  • Inputs can differ in length by thousands of digits, so the loop must keep going on the longer string after the shorter one ends.
  • The sum can be one digit longer than the longer input, so a leftover carry must become a final digit.

View on LeetCode

Hints

Hint 1

The problem blocks the easy route.

Hint 2

Walk both strings from their last characters toward their first.

Solution

Intuition

The problem blocks the easy route. Both inputs can hold 10,000 digits, which is far beyond any built-in integer type. You must do the arithmetic yourself, one digit at a time.

It is like a cashier counting two piles of coins from the top, handing only a small leftover pile to the next step. The carry variable is that leftover pile, and the buffer holds the answer coins laid out so far.

Addition on paper already works this way. You line up the rightmost digits, add each column, write the ones digit, and carry the tens digit to the left. In code, you run that schoolbook algorithm.

The carry is the only state that passes from one column to the next. Once you know the carry, each column depends only on its two digits. That is why a single pass from right to left is enough.

Watch the pattern animation

Worked example

Input: num1 = 4567, num2 = 789
Output: 5356
Explanation: Adding the columns from the right gives 7 + 9 = 16, so the digit is 6 and the carry is 1. The next columns give 6 + 8 + 1 = 15, then 5 + 7 + 1 = 13, then 4 + 0 + 1 = 5. Reading the digits from last to first gives 5356.

The Multiply Strings (Manual Simulation) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Multiply Strings (Manual Simulation)

Part of String Manipulation Patterns

Approach 1: Digit-by-digit carry simulationOptimalMultiply Strings (Manual Simulation)

Walk both strings from their last characters toward their first. At each column, add the two digits and the carry from the column to the right. Write the ones digit of that sum into the answer, and keep the tens digit as the carry for the next column.

Once a string runs out, treat its missing digits as 0. This lets one loop handle inputs of different lengths. The loop also keeps running while a carry remains, which produces the leading 1 when the sum gains a digit.

Digits come out least significant first, so you build the answer backwards and reverse it at the end. No faster route exists, because every digit must be read at least once.

Steps

  1. Set i to the last index of num1, j to the last index of num2, and carry to 0.
  2. While i is at least 0, or j is at least 0, or carry is not 0, repeat steps 3 to 6.
  3. Read the digit at num1[i] if i is valid, otherwise use 0. Read the digit at num2[j] the same way.
  4. Compute total = digit1 + digit2 + carry.
  5. Append total % 10 to the buffer, and set carry = total / 10.
  6. Decrement i and j.
  7. Reverse the buffer and return it as the answer.

Dry run

The example is num1 = 4567 and num2 = 789. Start with i = 3, j = 2, carry = 0, and an empty buffer.

Stepijdigit1digit2carry intotaldigit outcarry outbuffer
13279016616
221681155165
3105711331653
40-14015506535

After step 4, i and j are both -1 and carry is 0, so the loop ends. Reversing 6535 gives 5356, which matches the expected output.

Complexity

TimeO(max(n, m))
SpaceO(max(n, m)) for the output, O(1) auxiliary

Let n and m be the lengths of num1 and num2, and let L = max(n, m). The loop runs once per column, plus at most one extra step for a final carry. Each iteration does constant work: two character reads, a few arithmetic operations, and one append, so the loop costs O(L). Reversing the buffer touches at most L + 1 characters, which keeps the total at O(L).

The answer has at most L + 1 characters, so storing it takes O(L) space. The loop keeps only i, j, carry, and total, which are constant space. Beyond the returned answer, the auxiliary space is O(1).

PythonTested in our runner

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        digits = []
        i, j = len(num1) - 1, len(num2) - 1
        carry = 0
        while i >= 0 or j >= 0 or carry:
            # Use 0 for any digit past the front of its string
            d1 = int(num1[i]) if i >= 0 else 0
            d2 = int(num2[j]) if j >= 0 else 0
            total = d1 + d2 + carry
            digits.append(str(total % 10))
            carry = total // 10
            i -= 1
            j -= 1
        # Digits were collected least significant first
        return ''.join(reversed(digits))

Common mistakes

  • while i >= 0 and j >= 0 as the loop condition stops when the shorter string ends and drops the rest of the longer one. Use or so the loop reads the remaining digits.
  • while i >= 0 or j >= 0 without or carry > 0 loses the final carry. For 99 and 1 the loop ends with the carry still 1, and the answer comes out as 00 instead of 100.
  • total = d1 + d2 with the carry left out gives wrong columns. For 19 and 1 the second column must add the carry from the first, so the answer is 20, not 10.
  • Reading a digit with ord(num1[i]) or num1.charAt(i) and skipping the subtraction of '0' adds the character codes. The character '1' is code 49, so the column value is wrong.
  • Forgetting to reverse the buffer returns the digits in the wrong order. For the example the buffer holds 6535, and the answer is 5356.
  • Converting whole strings with int(), Integer.parseInt, or long breaks on large inputs. Python 3.11 and later reject int conversions above 4300 digits by default, and Java and C++ overflow far earlier.

Edge cases

  • Both inputs are 0: the loop runs once, appends 0, and returns 0.
  • Inputs 9 and 1: the first column carries, the loop runs one more step with both digits at 0, and the answer is 10.
  • Inputs 1 and 99999: the short string runs out after one step, and the loop keeps going on the long string, returning 100000.
  • Inputs 10 and 0: the zero operand adds nothing, so the answer is 10 with no leading zero in the output.
  • Two strings of 10^4 nines each: the carry chain covers every column, and the answer has 10001 digits beginning with 1.
  • A long string of 9s plus 1: the carry ripples through every column, producing 1 followed by 10^4 zeros.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Add Strings, with how to answer them.

Unlock the follow-ups

Add Strings FAQ

What is the time complexity of Add Strings?

The time complexity is O(max(n, m)), where n and m are the lengths of the two inputs. The loop visits each column once, and each column costs constant work. The reversal of the answer adds only a linear term.

Why use digit-by-digit simulation for Add Strings?

The inputs can hold 10,000 digits, which no built-in integer type can store. Column addition needs only the carry from the previous column, so a single pass from right to left gives the exact sum.

Can Add Strings be solved in O(1) extra space?

Beyond the returned answer, yes, because the loop keeps only a few integers. The answer itself needs O(max(n, m)) characters, so the total space cannot be O(1). The answer is part of the output, so most interviewers accept the constant auxiliary space.

Why does int() fail on long Add Strings inputs in Python?

Python 3.11 and later limit how many digits int() accepts from a string, with a default of 4300. Inputs with 10,000 digits raise a ValueError. The digit loop never converts the whole string, so it avoids this limit.

How do I handle a carry left over after both strings end?

Keep the loop running while carry is not 0. The loop then appends one more digit for each remaining carry, which is the leading 1 in cases such as 99 plus 1.

Asked at

See which companies ask this — Pro

Practise it