Add Strings - Problem

Given two non-negative integers num1 and num2 represented as strings, return the sum of num1 and num2 as a string.

Important constraints:

  • 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

The strings only contain digits and no leading zeros except the number 0 itself.

Input & Output

Example 1 — Basic Addition
$ Input: num1 = "11", num2 = "123"
Output: "134"
💡 Note: Step-by-step: 1+3=4 (rightmost), 1+2=3 (middle), 0+1=1 (leftmost), result is "134"
Example 2 — With Carry
$ Input: num1 = "456", num2 = "77"
Output: "533"
💡 Note: 6+7=13 (write 3, carry 1), 5+7+1=13 (write 3, carry 1), 4+0+1=5, result is "533"
Example 3 — Single Digits
$ Input: num1 = "0", num2 = "0"
Output: "0"
💡 Note: Edge case: 0 + 0 = 0, simplest possible addition

Constraints

  • 1 ≤ num1.length, num2.length ≤ 104
  • num1 and num2 consist of only digits
  • num1 and num2 don't have any leading zeros except for the zero itself

Visualization

Tap to expand
Add Strings - Optimized String Builder INPUT num1 = "11" 1 1 i=0 i=1 num2 = "123" 1 2 3 j=0 j=1 j=2 Process from right to left Input Values: num1 = "11" num2 = "123" ALGORITHM STEPS 1 Initialize Pointers i = len(num1)-1 = 1 j = len(num2)-1 = 2 2 Add Digits + Carry sum = digit1 + digit2 + carry digit = sum % 10 3 Update Carry carry = sum / 10 Prepend digit to result 4 Build Result Move pointers: i--, j-- Repeat until done Iteration Steps: 1+3+0=4 --> carry=0, digit=4 1+2+0=3 --> carry=0, digit=3 0+1+0=1 --> carry=0, digit=1 Result: "134" FINAL RESULT Sum String Built: 1 3 4 StringBuilder assembled right-to-left, then reversed Building Process: "" --> "4" --> "34" --> "134" (prepend each digit) Output: "134" OK - Sum computed! Key Insight: Use StringBuilder to efficiently build the result string. Process both strings from the end (like manual addition). Convert each character to digit using (char - '0'). Handle carry and different string lengths. Time: O(max(n,m)), Space: O(max(n,m)). No BigInteger or direct int conversion needed - pure character manipulation achieves the goal! TutorialsPoint - Add Strings | Optimized String Builder Approach
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 18
185.0K Views
Medium Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen