Add Binary (LeetCode 67): Solution and Explanation

Easy
Math
String
Bit Manipulation
Simulation

You receive two strings that each hold a binary number, and you must return their sum, also written as a binary string. The inputs can be far longer than any built-in integer type, so the addition has to be done digit by digit.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A tempting shortcut is to convert both strings to integers, add them, and convert back. In Python that even works because integers are unbounded, but in Java or C++ a string of a few hundred bits overflows long immediately, and interviewers usually want to see you do the arithmetic yourself. So the real question is how to add two numbers when all you have is their digits.

The answer is the same column addition you learned in school, just in base 2. Line the numbers up at their right ends, add the two digits in each column along with any carry from the column to the right, write down the low bit of that sum, and pass the high bit to the next column. In binary the column total is at most 1 + 1 + 1 = 3, so the digit you write is total % 2 and the carry you pass on is total // 2.

The only wrinkles are that the strings can have different lengths and that a carry can survive past the last digit of both inputs. Both disappear if the loop keeps running while either index is still valid or the carry is nonzero, and simply treats a missing digit as 0. Because you produce digits from least significant to most significant, you collect them in a list and reverse it once at the end instead of prepending to a string on every step.

Approach: Column addition with a carry

  1. Set i and j to the last index of a and b, start carry at 0, and create an empty result list.
  2. Loop while i >= 0, j >= 0, or carry is nonzero, so a final carry still produces a digit.
  3. Start each column with total = carry, then add int(a[i]) if i is in range and int(b[j]) if j is in range, moving each index one step left after reading it.
  4. Append str(total % 2) to result as the digit for this column.
  5. Set carry = total // 2, which is 1 when the column summed to 2 or 3 and 0 otherwise.
  6. After the loop, reverse result and join it into the final string.

Step-by-step example

a = "1011", b = "11"
  1. Start with i = 3, j = 1, carry = 0. Column one adds a[3] = 1 and b[1] = 1, so total = 2. Append 0 and set carry = 1.
  2. Column two: total = 1 + a[2] + b[0] = 1 + 1 + 1 = 3. Append 1 and keep carry = 1. Now j is -1.
  3. Column three: only a[1] = 0 remains, so total = 1 + 0 = 1. Append 1 and set carry = 0.
  4. Column four: total = 0 + a[0] = 1. Append 1 and keep carry = 0. Now i is -1 too, and with no carry left the loop ends.
  5. The list is [0, 1, 1, 1]. Reversed and joined, the answer is "1110", which is 14 in decimal, matching 11 + 3.

Code: Python, Java, C++

1class Solution:
2    def addBinary(self, a: str, b: str) -> str:
3        result = []
4        carry = 0
5        i, j = len(a) - 1, len(b) - 1
6
7        while i >= 0 or j >= 0 or carry:
8            total = carry
9            if i >= 0: total += int(a[i]); i -= 1
10            if j >= 0: total += int(b[j]); j -= 1
11            result.append(str(total % 2))
12            carry = total // 2
13
14        return ''.join(reversed(result))

Time and space complexity

Time

O(max(m, n))

Each loop iteration consumes at most one digit from each string, and there is at most one extra iteration for a final carry. The final reverse and join are linear in the output length, which is at most max(m, n) + 1.

Space

O(max(m, n))

The result list holds one character per output digit. Apart from the output itself, only a few integer variables are used.

Other approaches

Convert to integers (time O(m + n), space O(m + n))

In Python, bin(int(a, 2) + int(b, 2))[2:] gives the right answer because Python integers have arbitrary precision. In Java or C++ this fails for long inputs unless you reach for a big-integer class, and it hides the arithmetic the question is testing.

Bitwise XOR and AND loop (time O(m + n) per round, space O(m + n))

Treat the numbers as big integers and repeat sum = x ^ y, carry = (x & y) << 1 until the carry is zero. It shows off bit manipulation, but it still needs arbitrary-precision integers, and each round costs time proportional to the bit length.

Common mistakes

  • Stopping the loop when both indices run out. If the last column produced a carry, you lose the leading 1, so "1" + "1" would return "0" instead of "10".
  • Prepending to a string inside the loop. Each prepend copies the whole string, turning a linear algorithm into a quadratic one for long inputs.
  • Adding characters directly. In languages like Java, a.charAt(i) + b.charAt(j) adds character codes (48 for '0'), so you must subtract '0' first.
  • Aligning the strings from the left. Binary addition starts from the least significant bit, which is the last character, not the first.

Frequently asked questions

Why not just convert the binary strings to integers?

The inputs can be thousands of digits long, which overflows fixed-width integers in Java and C++. Even where it works, the conversion skips the digit-by-digit reasoning the problem is meant to exercise.

What is the maximum value of total in each column?

Three, when both digits are 1 and there is an incoming carry. That gives a written digit of 1 and a carry of 1, which is why total % 2 and total // 2 cover every case.

Can the result be longer than both inputs?

Yes, by exactly one digit at most. That happens when the final column produces a carry, which the loop handles by continuing while carry is nonzero.