Add Binary

Try to solve the Add Binary problem.

Statement#

Given two binary strings str1 and str2, return their sum as a binary string.

Constraints:

  • 11\leq str1.length , str2.length \leq 500500

  • str1 and str2 consist of 0 or 1 characters only.

  • Any string must not contain leading zeros except the string representing the binary form of 00.

Examples#

Created with Fabric.js 3.6.6 Sample Example 1 Input -------------------------------- Output str1 "100" str2 "111" binary sum "1011"

1 of 3

Created with Fabric.js 3.6.6 Input -------------------------------- Output Sample Example 2 str1 "111" str2 "111" binary sum "1110"

2 of 3

Created with Fabric.js 3.6.6 Sample Example 3 Input -------------------------------- Output str1 "11011" str2 "10001" binary sum "101100"

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Add Binary

1

What is the output if the following strings are given as input?
str1 = “1”
str2 = “1”

A)

“1”

B)

“11”

C)

“101”

D)

“10”

Question 1 of 40 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Iterate the two strings in reverse order using pointers, ptr1 and ptr2, respectively.

For each iteration, retrieve corresponding digits of the two strings.

Sum the retrieved digits and carry. Convert the sum into binary and add it to the result. Calculate carry for the next iteration.

If carry equals to 1 after the string traversal, append it to the result.

Reverse the result and return it.


Try it yourself#

Implement your solution in the following coding playground.

The optimal solution to this problem runs in O(max(n, m)) time and takes O(max(n, m)) space.

Python
usercode > main.py
Input #1
Input #2
Add Binary

You might want to review the way we learned to add numbers in elementary school, and apply the same method using binary arithmetic.

Getting Started

Solution: Add Binary