415. Add Strings
easyAdd 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^4num1 and num2 consist of only digits.num1 and num2 don't have any leading zeros except for the zero itself.
Examples
Example 1
num1 = "11", num2 = "123""134"Example 2
num1 = "456", num2 = "77""533"Example 3
num1 = "0", num2 = "0""0"Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
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
- 67. Add Binary
- 43. Multiply Strings
- 2. Add Two Numbers
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
More Math practice problems
- 7. Reverse Integer
- 8. String to Integer (atoi)
- 9. Palindrome Number
- 12. Integer to Roman
- 13. Roman to Integer
- 29. Divide Two Integers
- 38. Count and Say
- 43. Multiply Strings