Any idea how to address MLE solution (Python)


  • 0
    W

    Wrote the following iterative solution and passed 315/315 tests but with MLE. Any idea how to address it? Thanks in advance.

    class Solution(object):
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """
            # we don't return '0' for both-none situation to prevent leading zero issue
            if not (num1 and num2): return num1+num2
            if num1=='0': return num2
            if num2=='0': return num1
            sm = int(num1[-1])+int(num2[-1])
            if sm>9:
                # prevent leading zero
                if (not num1[:-1] and not num2[:-1]):
                    return '1'+str(sm-10)
                else:
                    return self.addStrings(self.addStrings(num1[:-1],num2[:-1]),'1')+str(sm-10)
            else:
                if (not num1[:-1] and not num2[:-1]):
                    return str(sm)
                else:   
                    return self.addStrings(num1[:-1],num2[:-1])+str(sm)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.