Approach 1Optimal▶ Animated
Add from the right, keep a carry
Same as Add Two Numbers, but the digits are bits. sum % 2 is the written bit; sum // 2 is the carry.
Walk both strings from the end. A leftover carry becomes a leading 1.
Algorithm
- i, j at the last characters, carry = 0.
- While either string or the carry remains, write
sum % 2and keepsum // 2. - Reverse the collected bits.
- Time
- O(n)
- Space
- O(n)
class Solution: def addBinary(self, a: str, b: str) -> str: i, j, carry = len(a) - 1, len(b) - 1, 0 out: list[str] = [] while i >= 0 or j >= 0 or carry: total = carry if i >= 0: total += int(a[i]) i -= 1 if j >= 0: total += int(b[j]) j -= 1 out.append(str(total % 2)) carry = total // 2 return "".join(reversed(out))