Back to Problem
Official 1802 views

Editorial: Add Binary Strings

by admin ·

8

1 Intuition

Schoolbook addition, base 2.

2 Approach

Add digit by digit from the right, tracking a carry, and reverse the collected digits at the end.

3 Complexity Analysis

Time O(max(n, m)), Space O(max(n, m)).

4 Solution Code

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i, j, carry, out = len(a) - 1, len(b) - 1, 0, []
        while i >= 0 or j >= 0 or carry:
            s = carry
            if i >= 0:
                s += int(a[i]); i -= 1
            if j >= 0:
                s += int(b[j]); j -= 1
            out.append(str(s % 2))
            carry = s // 2
        return ''.join(reversed(out))

5 Code Walkthrough

The reference solution below implements the approach step by step.