67. Add Binary

# Easy

This method is very slow.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i = len(a) - 1
        j = len(b) - 1
        result = [0 for x in range(max(len(a), len(b)))]
        result.append(0)
        x = len(result) - 1
        while i >= 0 and j >= 0:
            result[x] += int(a[i]) + int(b[j])
            if result[x] >= 2:
                result[x] = result[x]%2
                result[x-1] += 1
            i -= 1
            j -= 1
            x -= 1
            
        while i >= 0:
            result[x] += int(a[i])
            if result[x] == 2:
                result[x] = 0
                result[x-1] += 1
            x -= 1
            i -= 1
        while j >= 0:
            result[x] += int(b[j])
            if result[x] == 2:
                result[x] = 0
                result[x-1] += 1
            x -= 1
            j -= 1    
        
        s = ''
        if result[0] == 0:
            for i in range(1, len(result)):
                s += str(result[i])
        else:
            for i in range(len(result)):
                s += str(result[i])
        
        return s

Time complexity = O(max(m,n))O(max(m, n)) , Space complexity = O(max(m,n))O(max(m, n))

Last updated