Solution: Add Binary

Let's 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.

Solution#

The idea is to add binary numbers bit by bit while keeping track of any carry that occurs during the process. We iterate through both input strings in reverse order, calculate the sum and carry for each bit, update the result, and finally handle any remaining carry. The result is a valid binary sum of the two input binary strings.

Here are the steps of the algorithm:

  1. Initialize two variables:

    • result: This list will store the binary sum in reverse order.
    • carry: This variable will keep track of any carry that occurs during the addition process and is initialized with 00.
  2. Initialize two pointers to traverse the binary strings in reverse order:

    • ptr1: This pointer will traverse str1.

    • ptr2: This pointer will traverse str2.

  3. Traverse the strings in reverse order using the above pointers:

    • Extract the binary digits at the current position of ptr1 and ptr2. If either pointer goes beyond the string’s length, 00 is used for that string.

    • Calculate the sum, total_sum, of the current digits along with carry from the previous step.

    • The current_digit is computed as remainder of total_sum when divided by 22, representing the current bit value.

    • carry for the next iteration is updated by dividing total_sum by 22.

    • current_digit is appended to result.

    • Both ptr1 and ptr2 are moved one position to the left.

  4. Repeat step 33 until the strings are completely traversed.

  5. If there is still a carry left i.e, carry = 1, it’s appended to result.

  6. result contains binary sum in reverse order. It is reversed, converted to string, and returned.

Let’s look at the following illustration to get a better understanding of the solution:

canvasAnimation-image

1 of 10

canvasAnimation-image

2 of 10

canvasAnimation-image

3 of 10

canvasAnimation-image

4 of 10

canvasAnimation-image

5 of 10

canvasAnimation-image

6 of 10

canvasAnimation-image

7 of 10

canvasAnimation-image

8 of 10

canvasAnimation-image

9 of 10

canvasAnimation-image

10 of 10

Let’s implement the algorithm as discussed above:

Add Binary

Time complexity#

The time complexity of this solution is O(max(n,m))O{(max(n,m))}, where nn and mm are the lengths of strings str1 and str2 respectively. This is because the loop will run until the longest string has been traversed.

Space complexity#

The space complexity of this solution is O(max(n,m))O{(max(n,m))}, since we are using result to store the binary sum.

Add Binary

String to Integer (atoi)