Problem
Given two non-empty binary strings, return their sum as a binary string. The strings contain only '0' and '1' characters and have no leading zeros (except for the string "0" itself).
- Input: a =
"11", b ="1" - Output:
"100" - Explanation: 3 + 1 = 4, which is
100in binary.
Another example:
- Input: a =
"1010", b ="1011" - Output:
"10101" - Explanation: 10 + 11 = 21, which is
10101in binary.
Intuition
This is elementary school addition, but in base 2 instead of base 10. Start from the least significant (rightmost) bit, add the two digits plus any carry from the previous position, write down the result bit (total % 2), and pass the carry (total // 2) to the next position. The key insight: a carry can only be 0 or 1 in binary, so you never need more than one extra digit for the carry โ just loop until both strings and any remaining carry are exhausted.
Solution โ Bit-by-Bit Simulation
Walk both strings from right to left simultaneously, adding corresponding digits and a running carry. When one string runs out, treat missing digits as 0. Collect result bits in a list and reverse at the end.
- Set pointer
leftto the last index ofa, andrightto the last index ofb. Initializecarry = 0and an empty result list. - Loop while either pointer is in-bounds or carry is non-zero.
- Read
digit_afroma[left](or 0 if out-of-bounds) anddigit_bfromb[right](or 0 if out-of-bounds). Decrement both pointers. - Compute
total = digit_a + digit_b + carry. Appendtotal % 2to the result and setcarry = total // 2. - After the loop, reverse the result list and join into a string.
1def addBinary(self, a: str, b: str) -> str:
2 left = len(a) - 1
3 right = len(b) - 1
4 carry = 0
5 result = []
6
7 while left >= 0 or right >= 0 or carry:
8 digit_a = int(a[left]) if left >= 0 else 0
9 digit_b = int(b[right]) if right >= 0 else 0
10 total = digit_a + digit_b + carry
11 result.append(str(total % 2)) # current bit
12 carry = total // 2 # pass overflow to next position
13 left -= 1
14 right -= 1
15
16 return ''.join(reversed(result))Time: O(max(n, m)) โ each character in both strings is visited exactly once.
Space: O(max(n, m)) โ the result string holds at most max(n, m) + 1 characters.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Bit-by-Bit Simulation | O(max(n, m)) | O(max(n, m)) | Always โ works correctly for arbitrarily long binary strings in any language |
Common Mistakes
- Forgetting to flush the carry after both strings are exhausted โ
"1" + "1"should give"10"but without the final carry loop iteration you'd get"0". The loop condition must checkcarryin addition to the two pointers. - Using Python's
int(a, 2)shortcut in Java or C++ โ works fine in Python which has arbitrary-precision integers, but causes integer overflow in Java/C++ for binary strings longer than 63 bits. - Prepending to a string inside the loop โ
result = bit + resultlooks clean but is O(n) per prepend, making the total O(nยฒ). Append to a list (orStringBuilderin Java) and reverse once at the end instead. - Decrementing only the longer string's pointer โ when one string runs short, you must still decrement both pointers each iteration; the out-of-bounds check (
if left >= 0) handles the missing digit, not pointer manipulation. - Reading
a[left] - '0'without the out-of-bounds guard โ accessing a negative index in C++ is undefined behavior; in Python it wraps around silently. Always checkleft >= 0before readinga[left].
Related Problems
add-two-numbersโ same carry-propagation pattern, but digits are stored in linked list nodes instead of string charactersmultiply-stringsโ extends positional digit arithmetic to multiplication; the same right-to-left indexing appliesreverse-bitsโ direct bit manipulation on an integer's binary representationnumber-of-1-bitsโ counting set bits in a binary number, uses the same conceptual understanding of binary representationcounting-bitsโ computing bit counts for a range of numbers, reinforces binary addition patterns