67. Add Binary

Easy


Given two binary strings a and b, return their sum as a binary string.

 

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

 

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.




 class Solution:
    def addBinary(self, a: str, b: str) -> str:

        max_len = max(len(a), len(b))
        carry = 0
        a = a.zfill(max_len)
        b = b.zfill(max_len)

        ans = []
        for i in range(max_len-1, -1, -1):
            if a[i] == '1':
                carry+=1
            if b[i] == '1':
                carry+=1

            '''
            if both a, b and c  are 1, c is 3, we'll add 1
            if one of the 3 is 0, c will be 2 % 2 == 0 
            '''
            if carry%2 == 1: # c ==3
                ans.append("1")
            else:
                ans.append("0")
            carry //= 2

        if carry == 1:
            ans.append("1")

        ans.reverse()
        return "".join(ans)

Random Note


Amortized time is the way to express the time complexity when an algorithm has the very bad time complexity only once in a while besides the time complexity that happens most of time. Good example would be an ArrayList which is a data structure that contains an array and can be extended.