Skip to main content

415. Add Strings

easy

Add two non-negative integer strings without converting them to integers directly. Pure digit-by-digit grade-school addition — sometimes called the BigInt warm-up.

By Sam K., Founder, InterviewChamp.AI · Last verified

Problem

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Constraints

  • 1 <= num1.length, num2.length <= 10^4
  • num1 and num2 consist of only digits.
  • num1 and num2 don't have any leading zeros except for the zero itself.

Examples

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"

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Identical structure to Add Binary, just base 10 instead of base 2.

Hint 2

Walk from the right of each string. Maintain a carry initialized to 0.

Hint 3

At each step, sum = digit_a + digit_b + carry. Output digit is sum % 10; new carry is sum / 10.

Hint 4

Continue while either pointer is in bounds or carry > 0 (handles 99 + 1 = 100).

Solution approach

Reveal approach

Two pointers i = num1.length - 1 and j = num2.length - 1, plus a carry initialized to 0 and an output buffer. Loop while i >= 0 or j >= 0 or carry > 0: digit_a = (i >= 0) ? num1[i] - '0' : 0; same for digit_b; sum = digit_a + digit_b + carry; append (sum % 10) to the buffer; carry = sum / 10; decrement i and j. After the loop, reverse the buffer and return it. O(max(m, n)) time, O(max(m, n)) space for the output. The 'or carry > 0' loop condition handles the final-carry case (e.g., 99 + 1). This is the foundational subroutine for Multiply Strings and many BigInt operations.

Complexity

Time
O(max(m, n))
Space
O(max(m, n))

Related patterns

  • math
  • two-pointers
  • string-scan

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Google
  • Facebook

More Math practice problems

See all Math problems →