Home
DSA Patterns
Two Pointers
Add Binary
Add Binary (LeetCode 67)
Add Binary (LeetCode 67): add two binary strings with two pointers from the right and a carry: each column's sum mod 2 is the bit, sum / 2 the carry.
Problem Understanding
Add Binary: given two binary strings a and b, return their sum as a binary string.
Examples: "11" + "1" = "100", and "1010" + "1011" = "10101".
The Intuition: Column Addition in Base 2
Add the numbers the way you would on paper, right to left:
- Point
iandjat the last bit of each string. - A column's total is the carry plus the bits there, at most
1 + 1 + 1 = 3. - The bit to write is
total % 2, and the carry into the next column istotal / 2. - When one string runs out, treat its bits as 0; when both run out, a leftover carry still adds a bit.
It is the two pointers idea run from the ends of two strings at once. Multiply Strings uses the same right-to-left carry, with every digit pair instead of one column.
Add Binary Visualization
COLUMNS COUNT FROM THE RIGHT · CARRY SHOWN ABOVE THE NEXT COLUMN
START AT THE RIGHT
carry
a
b
sum
carry
0
sum
:
Start at the last bit of each string: i = 3, j = 3, carry = 0
Next
Column 0: carry 0 + a 0 + b 1 = 1. Write 1, carry 0
a
b
a and b are right-aligned above the sum, with the carry shown over the next column. Try Carry chain to watch one carry ripple through every column and create a new bit.
Add Binary Dry Run
Input: a = "1010", b = "1011"
| Column | a bit | b bit | carry in | total | write | carry out |
|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 1 | 1 | 0 |
| 1 | 1 | 1 | 0 | 2 | 0 | 1 |
| 2 | 0 | 0 | 1 | 1 | 1 | 0 |
| 3 | 1 | 1 | 0 | 2 | 0 | 1 |
| 4 | - | - | 1 | 1 | 1 | 0 |
Answer: written right to left 1, 0, 1, 0, 1, reversed: "10101".
Add Binary LeetCode Solution
One loop that runs while either string has bits or a carry is left. C fills a buffer from the end and then shifts the answer to the front so the returned pointer can be freed.
Add Binary Code
1var addBinary = function(a, b) {2 let i = a.length - 1, j = b.length - 1, carry = 0;3 const out = [];4 while (i >= 0 || j >= 0 || carry) {5 let total = carry;6 if (i >= 0) total += Number(a[i--]);7 if (j >= 0) total += Number(b[j--]);8 out.push(total % 2);9 carry = Math.floor(total / 2);10 }11 return out.reverse().join('');12};
Add Binary in Python, Java, C++, TypeScript and C
Add Binary in Python
class Solution:
def addBinary(self, a: str, b: str) -> str:
i, j, carry = len(a) - 1, len(b) - 1, 0
out = []
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))Add Binary in Java
class Solution {
public String addBinary(String a, String b) {
int i = a.length() - 1, j = b.length() - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || carry > 0) {
int total = carry;
if (i >= 0) total += a.charAt(i--) - '0';
if (j >= 0) total += b.charAt(j--) - '0';
sb.append(total % 2);
carry = total / 2;
}
return sb.reverse().toString();
}
}Add Binary in C++
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size() - 1, j = b.size() - 1, carry = 0;
string out;
while (i >= 0 || j >= 0 || carry) {
int total = carry;
if (i >= 0) total += a[i--] - '0';
if (j >= 0) total += b[j--] - '0';
out.push_back('0' + total % 2);
carry = total / 2;
}
reverse(out.begin(), out.end());
return out;
}
};Add Binary in TypeScript
function addBinary(a: string, b: string): string {
let i = a.length - 1, j = b.length - 1, carry = 0;
const out: number[] = [];
while (i >= 0 || j >= 0 || carry) {
let total = carry;
if (i >= 0) total += Number(a[i--]);
if (j >= 0) total += Number(b[j--]);
out.push(total % 2);
carry = Math.floor(total / 2);
}
return out.reverse().join('');
}Add Binary in C
char* addBinary(char* a, char* b) {
int i = strlen(a) - 1, j = strlen(b) - 1, carry = 0;
int len = (i > j ? i : j) + 2;
char* out = malloc(len + 1);
out[len] = '\0';
int k = len - 1;
while (i >= 0 || j >= 0 || carry) {
int total = carry;
if (i >= 0) total += a[i--] - '0';
if (j >= 0) total += b[j--] - '0';
out[k--] = '0' + total % 2;
carry = total / 2;
}
memmove(out, out + k + 1, len - k);
return out;
}Edge Cases & Common Mistakes
- Final carry:
"1" + "1"is"10"; keep looping while the carry is 1. - Different lengths: once a string is used up, add only the other bit and the carry.
- Both zero:
"0" + "0"is"0", a single column with no carry. - Building the string by prepending: prepending to a string each column is O(n²); append, then reverse once.
- Parsing with
int(a, 2): works in Python, but not in languages with fixed-width integers.
Summary
Walk both strings from the right with a carry. Each column writes total % 2 and carries total / 2; keep going while either string has bits or the carry is 1. Reverse the written bits. O(max(m, n)) time and space.
More practice: DSA interview questions with answers · patterns cheat sheet
