Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /0415 - Add Strings
    0415 - Add Strings
    0415 - Add Strings
    0415 - Add Strings

    0415 - Add Strings

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/add-strings/

    Solution 1 - Two Pointer from End

    Simulate digit-by-digit addition from right to left, just like manual addition. Use two pointers starting at the end of each string, sum corresponding digits plus any carry, and build the result in reverse.

    TimeComplexity:O(max(n,m))TimeComplexity: O(max(n, m))TimeComplexity:O(max(n,m))
    SpaceComplexity:O(max(n,m))SpaceComplexity: O(max(n, m))SpaceComplexity:O(max(n,m))
    """ 0415.1 - Solution 1 - Two Pointer from End """
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def addStrings(self, num1: str, num2: str) -> str:
            """Add Strings Function"""
            i, j = len(num1) - 1, len(num2) - 1
            carry = 0
            result = []
    
            while i >= 0 or j >= 0 or carry:
                a = int(num1[i]) if i >= 0 else 0
                b = int(num2[j]) if j >= 0 else 0
                total = a + b + carry
                carry, digit = divmod(total, 10)
                result.append(str(digit))
                i -= 1
                j -= 1
    
            return "".join(reversed(result))
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().addStrings("11", "123"))       # "134"
        print(Solution().addStrings("456", "77"))        # "533"
        print(Solution().addStrings("0", "0"))           # "0"
        print(Solution().addStrings("99", "1"))          # "100"
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()