15% off all plans & roadmaps Use code
See plansAdd Binary
- LeetCode 67
- Easy
- Array/Matrix Manipulation Patterns
- Plus One (Handling Carry)
Updated
TL;DR: Add the two strings from their last characters toward their first, carrying a 0 or 1 to the next column. Each column writes one bit, and the bits are reversed at the end.
Problem
Given two binary strings a and b, return their sum as a binary string.
Return the sum of the two numbers that a and b represent, written in binary.
Example 1
Input: a = "11", b = "1" Output: "100"
Example 2
Input: a = "1010", b = "1011" Output: "10101"
Constraints
1 <= a.length, b.length <= 10^4aandbcontain only the characters'0'and'1'.- Each string has no leading zeros, except the string
"0"itself.
Constraints that matter
- Lengths up to 10^4 rule out converting to a native integer, because 2^10000 does not fit in any fixed-width type.
- The two strings can have different lengths, so the loop must keep running until the longer string is used up.
- The sum can be one digit longer than the longer input, so the loop must keep going while a carry remains.
- Each digit is 0 or 1, so a column sum is at most 3. One carry bit is always enough.
Hints
Hint 1
Adding binary numbers works like adding decimal numbers on paper.
Hint 2
Walk both strings from their last characters toward their first.
Solution
Intuition
Adding binary numbers works like adding decimal numbers on paper. You start at the rightmost column, add the digits plus any carry from the column to the right, write one digit, and pass the carry left. This is the plus one with carry pattern. A number is a row of digits, and a carry moves one place to the left at a time.
Picture adding two long numbers on paper, one column at a time from the right. The buffer is the answer row you fill one digit at a time, and the carry is the small number you hold in your head for the next column.
You could convert both strings to integers and add them, but that fails here. A string of length 10^4 stands for a number near 2^10000, and no native integer type holds that. Python can handle it, but the problem exists to test the column logic, so you should write that logic yourself.
Each column sum is at most 1 + 1 + 1 = 3. A sum of 0 or 1 writes that digit and sends no carry. A sum of 2 or 3 writes the low bit, which is sum % 2, and sends a carry of 1, which is sum / 2. The division by two produces the carry directly, so you never need a separate branch for it.
The loop ends only when both strings are used up and no carry remains. A shorter string acts as if it had zeros on its left. You treat missing digits as 0 instead of padding the string.
Worked example
Input: a = "1", b = "11111111111111111111111111111111" Output: "100000000000000000000000000000000" Explanation: Adding 1 to a run of ones gives a carry through every column. The sum of 1 and 2^n - 1 is 2^n, which is a 1 followed by n zeros. The output has one more digit than b.
The Plus One (Handling Carry) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Plus One (Handling Carry)
Approach 1: Right-to-left digit addition with carryOptimalPlus One (Handling Carry)
Walk both strings from their last characters toward their first. At each column, add the digit from a, the digit from b, and the carry from the previous column. Use 0 for any string that has run out of digits.
Write the low bit of the sum into a buffer and pass the high bit forward as the new carry. The buffer receives the least significant bit first, so reverse it once at the end. The loop keeps going while either pointer is in range or the carry is 1.
Why it is correct. At every step, the buffer holds the low bits of the true sum, and the carry holds exactly the part that belongs to the next column. Column sums never exceed 3, so the carry is always 0 or 1 and no part of the sum is lost. Each column adds two bits and one carry, so no digit is skipped or counted twice.
Steps
- Set
ito the last index ofa,jto the last index ofb, andcarryto 0. - While
i >= 0, orj >= 0, orcarryis 1, start a new column. - Inside the column, add the digit at
iifi >= 0, and moveileft. Add the digit atjifj >= 0, and movejleft. - Compute
total = digits added + carry. - Append
total % 2to the buffer. - Set
carry = total / 2using integer division. - After the loop, reverse the buffer and return it as a string.
Dry run
Trace on the page's example, with a = "1" and b made of all ones. Let n be the length of b. After column 0, a is used up, so its digit counts as 0 in every later column.
| Step (from right) | a digit | b digit | carry in | total | bit written | carry out |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 0 | 2 | 0 | 1 |
| 1 to n-1 (same row each time) | 0 (a used up) | 1 | 1 | 2 | 0 | 1 |
| n | 0 | 0 (b used up) | 1 | 1 | 1 | 0 |
After step n the carry is 0 and both pointers are out of range, so the loop stops. The buffer holds n zeros followed by a 1. Reversing it gives a 1 followed by n zeros, which matches the expected output.
Complexity
| Time | O(max(n, m)) |
|---|---|
| Space | O(max(n, m)) |
Let n be the length of a and m be the length of b. The loop runs once per column, and there are max(n, m) columns plus at most one carry column. Each iteration does a fixed amount of work, so the loop costs O(max(n, m)).
The reverse step visits each buffered bit once, which is also O(max(n, m)). The buffer holds one character per column, so space is O(max(n, m)). The pointers and carry add only O(1) extra.
PythonTested in our runner
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = []
i, j = len(a) - 1, len(b) - 1
carry = 0
# Keep going while digits or a carry remain
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
# The low bit is written, the high bit is carried
res.append(str(total % 2))
carry = total // 2
# Bits were produced least significant first
return "".join(reversed(res))JavaTested in our runner
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
// Keep going while digits or a carry remain
while (i >= 0 || j >= 0 || carry > 0) {
int total = carry;
if (i >= 0) {
total += a.charAt(i) - '0';
i--;
}
if (j >= 0) {
total += b.charAt(j) - '0';
j--;
}
// Low bit goes to the buffer, high bit is carried
sb.append(total % 2);
carry = total / 2;
}
// Bits were produced least significant first
return sb.reverse().toString();
}
}C++Tested in our runner
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
string res;
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
// Keep going while digits or a carry remain
while (i >= 0 || j >= 0 || carry > 0) {
int total = carry;
if (i >= 0) {
total += a[i--] - '0';
}
if (j >= 0) {
total += b[j--] - '0';
}
// Low bit goes to the buffer, high bit is carried
res.push_back('0' + total % 2);
carry = total / 2;
}
// Bits were produced least significant first
reverse(res.begin(), res.end());
return res;
}
};JavaScriptTested in our runner
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
const res = [];
let i = a.length - 1;
let j = b.length - 1;
let carry = 0;
// Keep going while digits or a carry remain
while (i >= 0 || j >= 0 || carry > 0) {
let total = carry;
if (i >= 0) {
total += a.charCodeAt(i) - 48;
i--;
}
if (j >= 0) {
total += b.charCodeAt(j) - 48;
j--;
}
// Low bit goes to the buffer, high bit is carried
res.push(total % 2);
carry = Math.floor(total / 2);
}
// Bits were produced least significant first
return res.reverse().join("");
};GoTested in our runner
func addBinary(a string, b string) string {
res := make([]byte, 0, len(a)+len(b)+1)
i, j, carry := len(a)-1, len(b)-1, 0
// Keep going while digits or a carry remain
for i >= 0 || j >= 0 || carry > 0 {
total := carry
if i >= 0 {
total += int(a[i] - '0')
i--
}
if j >= 0 {
total += int(b[j] - '0')
j--
}
// Low bit goes to the buffer, high bit is carried
res = append(res, byte('0'+total%2))
carry = total / 2
}
// Bits were produced least significant first
for l, r := 0, len(res)-1; l < r; l, r = l+1, r-1 {
res[l], res[r] = res[r], res[l]
}
return string(res)
}C#Tested in our runner
using System;
using System.Text;
public class Solution {
public string addBinary(string a, string b) {
var sb = new StringBuilder();
int i = a.Length - 1;
int j = b.Length - 1;
int carry = 0;
// Keep going while digits or a carry remain
while (i >= 0 || j >= 0 || carry > 0) {
int total = carry;
if (i >= 0) {
total += a[i] - '0';
i--;
}
if (j >= 0) {
total += b[j] - '0';
j--;
}
// Low bit goes to the buffer, high bit is carried
sb.Append((char)('0' + total % 2));
carry = total / 2;
}
// Bits were produced least significant first
char[] arr = sb.ToString().ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}Common mistakes
while i >= 0 and j >= 0 or carrywith the wrong operators, orwhile i >= 0 and j >= 0alone. Usingandbetween the pointer checks stops early when one string is shorter. Useorso the longer string finishes.while i >= 0 or j >= 0:with no carry check. Adding1and1leaves a carry of 1 after the loop, and the leading 1 is lost. Addor carry > 0to the loop condition.if total == 2: carry = 1in place ofcarry = total // 2. A total of 3 also produces a carry of 1, so the branch misses it. Compute the carry with integer division.- Reading
a[i]without checkingi >= 0first. The shorter string runs out first and the index becomes -1, which crashes or reads the wrong character. Guard each read with its own check. - Returning the buffer without reversing it. The bits are written least significant first, so
"11"plus"1"returns"001"instead of"100". Reverse the buffer once after the loop. - Converting with
longorintin Java or C++, or withint(a, 2)in a language where the result is fixed width. Strings longer than about 63 bits overflow. Work digit by digit and never build the full number.
Edge cases
a = "0",b = "0": the loop writes one 0 and sends no carry, so the output is"0".a = "1",b = "1": column 0 gives total 2, so the output is"10".a = "1",b = "11111111": the carry travels through all eight columns, so the output is"100000000".a = "101",b = "0": the shorter string contributes 0 in every column, so the output is"101".- Both strings of length 10^4: the buffer grows to 10^4 characters or one more, and the loop runs at most 10^4 + 1 times.
aof length 1 andbof length 10^4 with all ones: the output has length 10^4 + 1 and starts with 1.
Follow-ups interviewers ask
- What if the two numbers are stored as linked lists of digits, with the most significant digit first?
- Push the digits of each list onto a stack, so the least significant digit is on top. Pop from both stacks in the same loop as before, and build the result as a linked list by prepending each new digit. Prepending gives the right order without a final reverse, and the extra stacks use O(max(n, m)) space.
- Can you do it with O(1) extra space?
- The output itself needs max(n, m) + 1 characters, so the output space cannot be O(1). The working memory can be O(1), though. Allocate the output once, write the bits from its right end, and drop a leading 0 at the end. The pointers and carry stay as they are.
- What if the strings are too large to hold in memory at once?
- Read both inputs in chunks from the end, since carries flow from right to left. Process one chunk pair at a time and keep only the carry between chunks. Write each result chunk to output as it finishes, in reverse order of production, which needs a reversed write or a temporary file.
Add Binary FAQ
What is the time complexity of Add Binary?
The time is O(max(n, m)), where n and m are the lengths of the two strings. The loop runs once per column, and each column does a fixed amount of work. The final reverse adds one more linear pass.
Why use a right-to-left carry loop for Add Binary?
Carries move from the least significant column to the most significant one, so right to left is the only order where each column already has its carry. Walking left to right would need to know future carries. Walking right to left handles the carry with one variable.
Can Add Binary be solved in O(1) extra space?
Not if you count the output, because the result needs max(n, m) + 1 characters at most. Apart from the output, the solution uses two indices and one carry, so the working memory is O(1). The loop writes into a buffer that becomes the output, so the buffer is not extra.
Why not convert the strings to integers?
Strings of length 10^4 represent numbers far larger than any native integer type. Java and C++ overflow, and even with a big integer library, the problem tests whether you can do the column arithmetic. The digit loop also works for any length without new types.
Does Python make Add Binary easy?
Python can compute bin(int(a, 2) + int(b, 2))[2:] in one line, because Python integers have no size limit. That answer works, but it skips the carry logic the interviewer wants to see. The bin() function adds a 0b prefix, so the slice [2:] must remove it.
Asked at
See which companies ask this — Pro
Related problems
- Plus One · same technique: Plus One (Handling Carry)
- Add Strings · same technique: Plus One (Handling Carry)
- Add to Array-Form of Integer · same technique: Plus One (Handling Carry)
- Multiply Strings · same technique: Plus One (Handling Carry)
- Two Sum · same pattern: Array/Matrix Manipulation Patterns
- Contains Duplicate · same pattern: Array/Matrix Manipulation Patterns
- Happy Number · same pattern: Array/Matrix Manipulation Patterns
- Valid Anagram · same pattern: Array/Matrix Manipulation Patterns
- Valid Palindrome · same pattern: Array/Matrix Manipulation Patterns
- Missing Number · same pattern: Array/Matrix Manipulation Patterns