Add Binary

Easy

Topics
MathStringBit ManipulationSimulation

Given two binary strings s and t, return their sum as a binary string.

The inputs carry no leading zeros apart from "0" itself, and the answer must not either.

LeetCode names the arguments a and b; the harness here calls them s and t. They are the two addends and order does not matter.

Example 1

s 11t 1sum100012
a binary digit
Written 11 over 1, the two are aligned on their right-hand ends, because a column of this addition is a single place value and the inputs can be different lengths. A column adds to 0, 1, 2 or 3, and the half that exceeds one digit carries into the column to its left. The sum is 3 digits wide against 2 for the longer input, so a carry survived past the leftmost column and had to be written as a new digit.
These are strings, not numbers; at the stated length they do not fit an integer.
Input:  s = "11", t = "1"
Output: "100"
Explanation: 3 + 1 = 4.

Example 2

s 1010t 1011sum1010101234
a binary digit
Input:  s = "1010", t = "1011"
Output: "10101"
Explanation: 10 + 11 = 21.

Example 3

s0t0sum00
a binary digit
No carry escaped the leftmost column here, so the sum is exactly as wide as the longer input.
Input:  s = "0", t = "0"
Output: "0"
Explanation: The one case where a leading zero is the whole answer.

Constraints

  • 1 <= s.length, t.length <= 10^4
  • s and t consist only of the characters 0 and 1
  • Each string has no leading zero except when it is exactly "0"
Editorial — intuition, approach, complexity and pitfalls

Intuition

The reason this is not a one-liner is the input size. Ten thousand binary digits is a number with about three thousand decimal digits, so converting to an integer, adding, and converting back is only available in languages with arbitrary-precision integers. In Java or C++ it overflows long before the limit.

So do what you were taught at school: add from the right, one column at a time, carrying into the next. The only difference from decimal is that a column sum of 2 produces digit 0 carry 1, and a sum of 3 produces digit 1 carry 1.

The tidy way to handle unequal lengths is to treat a position past the end of a string as a 0 digit, rather than padding one input to match the other. That removes a whole branch.

The carry has to be checked once more after the loop. Adding "1" to "1" is the smallest case where the answer is longer than either input, and dropping that final carry is the usual bug.

Approach

  1. Set two cursors at the last character of each string and a carry of 0.
  2. While either cursor is still in range, or the carry is non-zero, take the digit under each cursor, treating out-of-range as 0.
  3. Sum the two digits and the carry. Append sum % 2 to the output and set the carry to sum / 2.
  4. Move both cursors left and repeat.
  5. The digits were produced least significant first, so reverse the collected output before returning it.

Walkthrough

s = "1010", t = "1011"

       1 0 1 0
     + 1 0 1 1

column by column, right to left
   col 0:  0 + 1 + carry 0 = 1  ->  digit 1, carry 0
   col 1:  1 + 1 + carry 0 = 2  ->  digit 0, carry 1
   col 2:  0 + 0 + carry 1 = 1  ->  digit 1, carry 0
   col 3:  1 + 1 + carry 0 = 2  ->  digit 0, carry 1
   done, carry 1 remains      ->  digit 1

collected least significant first: 1 0 1 0 1
reversed:                          1 0 1 0 1

answer "10101"

the case that catches a dropped carry
   s = "1", t = "1"
   col 0: 1 + 1 = 2 -> digit 0, carry 1
   loop ends; the carry still has to be written
   answer "10", not "0"

Complexity

  • Time — O(max(m, n)): one column per digit of the longer input, plus at most one more for the carry.
  • Space — O(max(m, n)): the output, which is at most one digit longer than the longer input.

Common Pitfalls

  • Converting to int and back. It passes in Python and overflows in Java and C++ at the stated limit.
  • Dropping the final carry, so "1" + "1" returns "0".
  • Forgetting to reverse. The digits come out least significant first.
  • Padding the shorter string with zeros and then mishandling the index. Treating out-of-range as 0 is simpler and has no off-by-one.
  • Building the result by prepending to a string in a loop. That is quadratic at ten thousand digits; collect and reverse instead.

Full Solution — all languages

class Solution:
    def addBinary(self, s, t):
        i, j = len(s) - 1, len(t) - 1
        carry = 0
        out = []

        # The carry in the condition is what writes the extra leading digit.
        while i >= 0 or j >= 0 or carry:
            total = carry
            if i >= 0:
                total += int(s[i])
                i -= 1
            if j >= 0:
                total += int(t[j])
                j -= 1
            out.append(str(total % 2))
            carry = total // 2

        return "".join(reversed(out))
SensAI
Beta
Tap the mic to stop voice mode