15% off all plans & roadmaps Use code

See plans

Add Binary

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^4
  • a and b contain 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.

View on LeetCode

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.

Watch the pattern animation

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 infographic

Solution pattern

Plus One (Handling Carry)

Part of Array/Matrix Manipulation Patterns

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

  1. Set i to the last index of a, j to the last index of b, and carry to 0.
  2. While i >= 0, or j >= 0, or carry is 1, start a new column.
  3. Inside the column, add the digit at i if i >= 0, and move i left. Add the digit at j if j >= 0, and move j left.
  4. Compute total = digits added + carry.
  5. Append total % 2 to the buffer.
  6. Set carry = total / 2 using integer division.
  7. 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 digitb digitcarry intotalbit writtencarry out
0110201
1 to n-1 (same row each time)0 (a used up)11201
n00 (b used up)1110

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

TimeO(max(n, m))
SpaceO(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))

Common mistakes

  • while i >= 0 and j >= 0 or carry with the wrong operators, or while i >= 0 and j >= 0 alone. Using and between the pointer checks stops early when one string is shorter. Use or so the longer string finishes.
  • while i >= 0 or j >= 0: with no carry check. Adding 1 and 1 leaves a carry of 1 after the loop, and the leading 1 is lost. Add or carry > 0 to the loop condition.
  • if total == 2: carry = 1 in place of carry = 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 checking i >= 0 first. 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 long or int in Java or C++, or with int(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.
  • a of length 1 and b of 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

Practise it