Talentd
FleetCode
Make and follow sheets.Sign in

Add Strings solution and explanation

EasyMathSimulationString6 min read52.1% acceptanceUpdated 9 Apr 2026
Add Strings | Leetcode 415 Solution in HindiPepcoding · 10:45 · 14K viewsWatch on YouTube
9 more videos on this problem
  1. Add Strings | Leetcode 415 Solution in HindiPepcoding · 10:45 · 14K views
  2. ADD STRINGS | PYTHON SOLUTION | LEETCODE 415Cracking FAANG · 10:24 · 8K views
  3. 415. Add Strings || Java || Leetcode || HindiCoding Sphere · 10:25 · 6K views
  4. Add Strings | Leetcode 415Technosage · 8:21 · 6K views
  5. Add Strings || Leetcode 415 || Variant Question Big Tech Actually AsksCoding with Minmer · 28:03 · 5K views
  6. Add Strings | Math | Strings | Simulation | 415 LeetCode | Day 09CodeWithSunny · 6:37 · 2K views
  7. Leetcode 415 - Add Strings (JAVA Solution Explained!)LC Bear · 7:04 · 1K views
  8. Add Strings | Leetcode 415 | Live coding sessionCoding Decoded · 6:15 · 1K views
  9. 415. Add Strings | Leetcode problem no. 415. | C++ | hindiWaytoCode · 5:45 · 546 views
  10. Add Strings || Leetcode 415constantinirimia · 11:25 · 263 views

The 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.

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:

  • 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.

Approach overview

Problem Overview: You are given two non‑negative integers stored as strings. The task is to return their sum, also as a string, without converting the entire string into an integer. The challenge is handling digit addition and carry manually, similar to how you add numbers on paper.

Approach 1: Reverse and Traverse (O(n) time, O(n) space)

This method reverses both strings so the least significant digits appear first. After reversing, iterate from index 0 while adding corresponding digits and maintaining a carry. Each step computes digitSum = d1 + d2 + carry, appends digitSum % 10 to the result, and updates carry = digitSum / 10. Continue until both strings are fully processed and the carry is handled. The result string is reversed again to restore correct order. Time complexity is O(n) because every digit is processed once, and space complexity is O(n) due to storing reversed strings and the output.

This approach is straightforward and mirrors manual addition closely. Reversing the strings simplifies index handling because digits align naturally from least significant to most significant.

Approach 2: Character by Character Addition Using Two Pointers (O(n) time, O(1) extra space)

This approach avoids reversing strings by using two pointers starting from the end of each string. Pointer i begins at num1.length() - 1 and pointer j at num2.length() - 1. At each step, convert characters to digits, compute their sum with the current carry, and append the resulting digit. Decrement pointers and repeat until both pointers are exhausted and no carry remains.

The digits are generated from least significant to most significant, so the result is typically built using a dynamic buffer and reversed once at the end. Time complexity remains O(n), where n is the maximum length of the two strings. Extra space is O(1) excluding the output string. This method is commonly preferred because it avoids modifying the input and keeps memory overhead minimal.

The problem mainly tests understanding of string manipulation, elementary math operations, and iterative simulation of digit-by-digit addition.

Recommended for interviews: The two‑pointer approach is the expected solution. Interviewers want to see that you can simulate addition from right to left while managing carry efficiently. The reverse‑and‑traverse method still demonstrates correct reasoning, but the pointer approach shows stronger control over string traversal and space optimization.

Approach 1: Reverse and Traverse

This approach involves reversing both input strings, then iterating through them to sum up each digit, similar to manual addition from the rightmost digit. This technique simplifies handling the carry over during addition.

def addStrings(num1: str, num2: str) -> str:
    result = []
    carry = 0
    i, j = len(num1) - 1, len(num2) - 1

    while i >= 0 or j >= 0 or carry:
        x = int(num1[i]) if i >= 0 else 0
        y = int(num2[j]) if j >= 0 else 0

        sum_ = x + y + carry
        result.append(str(sum_ % 10))
        carry = sum_ // 10

        i -= 1
        j -= 1

    return ''.join(reversed(result))

# Example usage:
print(addStrings("11", "123"))
public class AddStrings {
    public static void main(String[] args) {
        String num1 = "456";
        String num2 = "77";
        System.out.println(addStrings(num1, num2));
    }

    public static String addStrings(String num1, String num2) {
        StringBuilder result = new StringBuilder();
        int carry = 0, i = num1.length() - 1, j = num2.length() - 1;

        while (i >= 0 || j >= 0 || carry != 0) {
            int x = (i >= 0) ? num1.charAt(i) - '0' : 0;
            int y = (j >= 0) ? num2.charAt(j) - '0' : 0;
            int sum = x + y + carry;

            result.append(sum % 10);
            carry = sum / 10;

            i--; j--;
        }

        return result.reverse().toString();
    }
}
#include <iostream>
#include <string>
using namespace std;

string addStrings(string num1, string num2) {
    string result = "";
    int carry = 0, i = num1.size() - 1, j = num2.size() - 1;

    while (i >= 0 || j >= 0 || carry) {
        int sum = carry;
        if (i >= 0) sum += num1[i--] - '0';
        if (j >= 0) sum += num2[j--] - '0';

        result += (sum % 10) + '0';
        carry = sum / 10;
    }

    reverse(result.begin(), result.end());
    return result;
}

int main() {
    string num1 = "11", num2 = "123";
    cout << addStrings(num1, num2) << endl;
    return 0;
}
function addStrings(num1, num2) {
    let carry = 0, i = num1.length - 1, j = num2.length - 1;
    let result = [];

    while (i >= 0 || j >= 0 || carry !== 0) {
        const x = i >= 0 ? +num1[i] : 0;
        const y = j >= 0 ? +num2[j] : 0;

        const sum = x + y + carry;
        result.push(sum % 10);
        carry = Math.floor(sum / 10);

        i--;
        j--;
    }

    return result.reverse().join('');
}

// Example usage:
console.log(addStrings("11", "123"));
#include <stdio.h>
#include <string.h>
char* addStrings(char* num1, char* num2) {
    static char result[10005];
    memset(result, 0, sizeof(result));
    int len1 = strlen(num1), len2 = strlen(num2);
    int carry = 0, i = 0;

    while (len1 > 0 || len2 > 0 || carry) {
        if (len1 > 0) carry += num1[--len1] - '0';
        if (len2 > 0) carry += num2[--len2] - '0';
        result[i++] = (carry % 10) + '0';
        carry /= 10;
    }

    result[i] = '\0'; // Null-terminate the string

    for (int j = 0; j < i / 2; j++) { // Reverse result
        char temp = result[j];
        result[j] = result[i - j - 1];
        result[i - j - 1] = temp;
    }
    return result;
}

int main() {
    char num1[] = "456";
    char num2[] = "77";
    printf("%s\n", addStrings(num1, num2));
    return 0;
}
using System;
using System.Text;

public class AddStrings {
    public static void Main(string[] args) {
        Console.WriteLine(AddStrings("0", "0"));
    }

    public static string AddStrings(string num1, string num2) {
        var result = new StringBuilder();
        int carry = 0, i = num1.Length - 1, j = num2.Length - 1;

        while (i >= 0 || j >= 0 || carry != 0) {
            int x = (i >= 0) ? num1[i] - '0' : 0;
            int y = (j >= 0) ? num2[j] - '0' : 0;

            int sum = x + y + carry;
            result.Append(sum % 10);
            carry = sum / 10;

            i--;
            j--;
        }

        char[] resultArray = result.ToString().ToCharArray();
        Array.Reverse(resultArray);
        return new string(resultArray);
    }
}

This Python implementation efficiently processes input strings num1 and num2 using a loop to sum digits from back to front, handling carries. The final sum is built using a list for ease of reversal and joined into a single string result.

Complexity

Time Complexity: O(n), where n is the maximum length of num1 or num2.
Space Complexity: O(n), due to the result list used to store interim calculation results.

Try this approach in the editor

Approach 2: Character by Character Addition Using Two Pointers

This approach deploys two pointers, initially positioned at the end of each input string. We process each character one by one, moving the pointers from the rightmost end towards the start of each string. This allows us to readily manage the carry as we compute the sum step-by-step.

def addStrings(num1, num2):
    i, j = len(num1) - 1, len(num2) - 1
    carry = 0
    result = []

    while i >= 0 or j >= 0 or carry:
        x = int(num1[i]) if i >= 0 else 0
        y = int(num2[j]) if j >= 0 else 0

        sum_ = x + y + carry
        result.append(str(sum_ % 10))
        carry = sum_ // 10

        i -= 1
        j -= 1

    return ''.join(reversed(result))

# Example
print(addStrings("101", "900"))
public class AddStrings {
    public static void main(String[] args) {
        System.out.println(addStrings("456", "56"));
    }

    public static String addStrings(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
        StringBuilder result = new StringBuilder();

        while (i >= 0 || j >= 0 || carry > 0) {
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            int sum = x + y + carry;
            result.append(sum % 10);
            carry = sum / 10;
            i--;
            j--;
        }

        return result.reverse().toString();
    }
}
#include <iostream>
#include <string>
using namespace std;

string addStrings(string num1, string num2) {
    int i = num1.size() - 1, j = num2.size() - 1;
    int carry = 0;
    string result = "";

    while (i >= 0 || j >= 0 || carry) {
        int x = i >= 0 ? num1[i--] - '0' : 0;
        int y = j >= 0 ? num2[j--] - '0' : 0;
        int sum = x + y + carry;

        result = to_string(sum % 10) + result;
        carry = sum / 10;
    }

    return result;
}

int main() {
    cout << addStrings("456", "77") << endl;
    return 0;
}
function addStrings(num1, num2) {
    let carry = 0;
    let i = num1.length - 1;
    let j = num2.length - 1;
    let result = [];

    while (i >= 0 || j >= 0 || carry !== 0) {
        const x = i >= 0 ? parseInt(num1.charAt(i)) : 0;
        const y = j >= 0 ? parseInt(num2.charAt(j)) : 0;
        const sum = x + y + carry;
        result.push(sum % 10);
        carry = Math.floor(sum / 10);
        i--;
        j--;
    }

    return result.reverse().join('');
}

// Example usage:
console.log(addStrings("314", "256"));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* addStrings(char* num1, char* num2) {
    int len1 = strlen(num1), len2 = strlen(num2);
    int maxLength = len1 > len2 ? len1 : len2;
    char* result = (char*)malloc(maxLength + 2);
    result[maxLength + 1] = '\0';

    int carry = 0, index = maxLength;

    len1--;
    len2--;

    while (len1 >= 0 || len2 >= 0 || carry) {
        int x = (len1 >= 0) ? num1[len1--] - '0' : 0;
        int y = (len2 >= 0) ? num2[len2--] - '0' : 0;

        int sum = x + y + carry;
        result[index--] = (sum % 10) + '0';
        carry = sum / 10;
    }

    return &result[index + 1];
}

int main() {
    char num1[] = "99";
    char num2[] = "1";
    printf("%s\n", addStrings(num1, num2));
    return 0;
}
using System;
using System.Text;

public class AddStrings {
    public static void Main(string[] args) {
        Console.WriteLine(AddStrings("123", "87"));
    }

    public static string AddStrings(string num1, string num2) {
        int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
        StringBuilder result = new StringBuilder();

        while (i >= 0 || j >= 0 || carry > 0) {
            int x = i >= 0 ? num1[i] - '0' : 0;
            int y = j >= 0 ? num2[j] - '0' : 0;
            int sum = x + y + carry;
            result.Append(sum % 10);
            carry = sum / 10;
            i--;
            j--;
        }

        char[] resultArray = result.ToString().ToCharArray();
        Array.Reverse(resultArray);
        return new string(resultArray);
    }
}

The Python function addStrings handles addition across variable-length strings via iteration in reverse order, merging carry logic with character processing. Utilization of int type conversion allows precise digit handling, supporting list-based result formation for concise finalization.

Complexity

Time Complexity: O(n), reflecting traversal over the longest input string.
Space Complexity: O(n), to store computed result segments.

Try this approach in the editor

Approach 3: Two Pointers

We use two pointers i and j to point to the end of the two strings respectively, and start adding bit by bit from the end. Each time we take out the corresponding digits a and b, calculate their sum a + b + c, where c represents the carry from the last addition. Finally, we append the units digit of a + b + c to the end of the answer string, and then take the tens digit of a + b + c as the value of the carry c, and loop this process until the pointers of both strings have pointed to the beginning of the string and the value of the carry c is 0.

Finally, reverse the answer string and return it.

The time complexity is O(max(m, n)), where m and n are the lengths of the two strings respectively. Ignoring the space consumption of the answer string, the space complexity is O(1).

The following code also implements string subtraction, refer to the subStrings(num1, num2) function.

function addStrings(num1: string, num2: string): string {
    let i = num1.length - 1;
    let j = num2.length - 1;
    const ans: number[] = [];
    for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) {
        c += i < 0 ? 0 : +num1[i];
        c += j < 0 ? 0 : +num2[j];
        ans.push(c % 10);
        c = Math.floor(c / 10);
    }
    return ans.reverse().join('');
}

function subStrings(num1: string, num2: string): string {
    const m = num1.length;
    const n = num2.length;
    const neg = m < n || (m == n && num1 < num2);
    if (neg) {
        const t = num1;
        num1 = num2;
        num2 = t;
    }
    let i = num1.length - 1;
    let j = num2.length - 1;
    const ans: number[] = [];
    for (let c = 0; i >= 0; --i, --j) {
        c = +num1[i] - c;
        if (j >= 0) {
            c -= +num2[j];
        }
        ans.push((c + 10) % 10);
        c = c < 0 ? 1 : 0;
    }
    while (ans.length > 1 && ans.at(-1) === 0) {
        ans.pop();
    }
    return (neg ? '-' : '') + ans.reverse().join('');
}
func addStrings(num1 string, num2 string) string {
	i, j := len(num1)-1, len(num2)-1
	ans := []byte{}
	for c := 0; i >= 0 || j >= 0 || c > 0; i, j = i-1, j-1 {
		if i >= 0 {
			c += int(num1[i] - '0')
		}
		if j >= 0 {
			c += int(num2[j] - '0')
		}
		ans = append(ans, byte(c%10+'0'))
		c /= 10
	}
	for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
		ans[i], ans[j] = ans[j], ans[i]
	}
	return string(ans)
}

func subStrings(num1 string, num2 string) string {
	m, n := len(num1), len(num2)
	neg := m < n || (m == n && num1 < num2)
	if neg {
		num1, num2 = num2, num1
	}
	i, j := len(num1)-1, len(num2)-1
	ans := []byte{}
	for c := 0; i >= 0; i, j = i-1, j-1 {
		c = int(num1[i]-'0') - c
		if j >= 0 {
			c -= int(num2[j] - '0')
		}
		ans = append(ans, byte((c+10)%10+'0'))
		if c < 0 {
			c = 1
		} else {
			c = 0
		}
	}
	for len(ans) > 1 && ans[len(ans)-1] == '0' {
		ans = ans[:len(ans)-1]
	}
	if neg {
		ans = append(ans, '-')
	}
	for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
		ans[i], ans[j] = ans[j], ans[i]
	}
	return string(ans)
}
class Solution {
    fun addStrings(num1: String, num2: String): String {
        val result = mutableListOf<Int>()

        val chars_1 = num1.toCharArray()
        val chars_2 = num2.toCharArray()
        var over = 0
        var i = num1.length
        var j = num2.length

        while (i > 0 || j > 0 || over > 0) {
            val a = if (i > 0) chars_1[--i] - '0' else 0
            val b = if (j > 0) chars_2[--j] - '0' else 0
            val sum = a + b + over
            over = sum / 10
            result.add(sum % 10)
        }

        return result.reversed().joinToString("")
    }
}
impl Solution {
    pub fn add_strings(num1: String, num2: String) -> String {
        let mut res = vec![];
        let s1 = num1.as_bytes();
        let s2 = num2.as_bytes();
        let (mut i, mut j) = (s1.len(), s2.len());
        let mut is_over = false;
        while i != 0 || j != 0 || is_over {
            let mut sum = if is_over { 1 } else { 0 };
            if i != 0 {
                sum += (s1[i - 1] - b'0') as i32;
                i -= 1;
            }
            if j != 0 {
                sum += (s2[j - 1] - b'0') as i32;
                j -= 1;
            }
            is_over = sum >= 10;
            res.push((sum % 10).to_string());
        }
        res.into_iter().rev().collect()
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Reverse and Traverse

Time Complexity: O(n), where n is the maximum length of num1 or num2.
Space Complexity: O(n), due to the result list used to store interim calculation results.

Character by Character Addition Using Two Pointers

Time Complexity: O(n), reflecting traversal over the longest input string.
Space Complexity: O(n), to store computed result segments.

Two Pointers–

Complexity analysis

ApproachTimeSpaceWhen to Use
Reverse and TraverseO(n)O(n)When simplicity matters and reversing strings is acceptable
Two Pointers from EndO(n)O(1) extraBest general solution; avoids reversing and minimizes memory usage

Frequently asked questions

Is Add Strings easy or hard?

Add Strings is classified as an Easy problem on LeetCode. The logic mirrors elementary school addition but requires careful handling of carry, pointer movement, and string construction without converting the entire number to an integer.

How to solve Add Strings in O(n)?

Traverse both strings from the last character using two pointers. Convert each character to its numeric digit, add them with a carry value, and append the result digit. Continue until both pointers are exhausted and handle any remaining carry. Each digit is processed once, giving O(n) time complexity.

What is the best approach for Add Strings?

The two‑pointer approach starting from the end of each string is considered the best solution. It simulates manual addition by processing digits from right to left while maintaining a carry value. The algorithm runs in O(n) time and uses O(1) extra space excluding the output string.

What data structure is used in Add Strings?

The solution mainly uses string traversal and a dynamic result buffer such as a string builder or list. Two integer pointers track positions in the input strings, and a carry variable maintains overflow between digit additions.

What is the time complexity of Add Strings?

The time complexity is O(n), where n is the maximum length of the two input strings. Each digit from both strings is processed once during the addition simulation. Space complexity is O(1) extra if using the two‑pointer approach, aside from the result string.

Add Strings Python or Java solution approach

In both Python and Java, iterate from the end of each string using indices. Convert characters to digits using subtraction like `c - '0'` in Java or `int(c)` in Python, compute the sum with carry, append the result digit, and finally reverse the constructed string.

Is Add Strings asked at Google, Amazon, or Meta?

Add Strings is a common interview-style question used by companies like Amazon, Google, and Meta to test string manipulation and basic algorithmic thinking. It evaluates whether candidates can simulate arithmetic operations without relying on built-in big integer conversions.

Comments

Now write it yourselfClose this page and solve Add Strings in the editor, without looking.
Practise Add Strings