Add Two Binary Strings

Implement addBinary

Given two binary strings a and b, return their sum, also as a binary string. This is elementary-school addition, just in base 2 instead of base 10 — walk both strings from the rightmost digit, add corresponding digits plus any carry from the previous position, and keep the overflow as a carry into the next position. The only real design decision is HOW to build the result string as you go: strings are immutable, so repeatedly gluing a new digit onto the FRONT forces a full copy every time. Appending to the end instead — then reversing once at the finish — does the same amount of real work in a fraction of the total time.

Example 1:

Input: a = "1010", b = "1011"

Output: "10101"

Example 2:

Input: a = "11", b = "1"

Output: "100"

Example 3:

Input: a = "0", b = "0"

Output: "0"

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ a.length, b.length ≤ 10⁴
  • a and b consist only of the characters '0' or '1'
  • Neither a nor b has leading zeros, except the string "0" itself

a =

1010

b =

1011