Leetcode #67: Add Binary
In this guide, we solve Leetcode #67 Add Binary in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Bit Manipulation, Math, String, Simulation
Intuition
The problem structure lets us track state with bitwise operations.
Bit operations are constant time and avoid extra memory.
Approach
Apply XOR/AND/OR and shifts to maintain the required invariant.
Aggregate the result in a single pass.
Steps:
- Identify a bitwise invariant.
- Combine values with bit operations.
- Return the aggregated result.
Example
Input: a = "11", b = "1"
Output: "100"
Python Solution
class Solution:
def addBinary(self, a: str, b: str) -> str:
ans = []
i, j, carry = len(a) - 1, len(b) - 1, 0
while i >= 0 or j >= 0 or carry:
carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j]))
carry, v = divmod(carry, 2)
ans.append(str(v))
i, j = i - 1, j - 1
return "".join(ans[::-1])
Complexity
The time complexity is , where and are the lengths of strings and respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.