Taro Logo

Add Binary

#241 Most AskedEasy
0 views
Topics:
StringsBit Manipulation

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible length of the input binary strings `a` and `b`?
  2. Can the input strings be empty, or contain only zeros, and should leading zeros be preserved in the final output unless the result itself is zero?
  3. Are the input strings guaranteed to contain only valid binary characters ('0' and '1'), or do I need to handle invalid characters?
  4. Should I implement the addition logic manually bit-by-bit, or are built-in arbitrary-precision arithmetic features/libraries allowed?
  5. How should I handle cases where one input string is significantly longer than the other?

Brute Force Solution

Approach

Imagine you have two numerical sequences written in ones and zeros, and you need to find their combined total. The brute force approach translates these binary sequences into standard everyday numbers, adds those normal numbers together, and then translates the final result back into ones and zeros.

Here's how the algorithm would work step-by-step:

  1. Take the first sequence of ones and zeros and convert it into a standard everyday number by calculating its value.
  2. Take the second sequence of ones and zeros and also convert it into a standard everyday number by calculating its value.
  3. Add the two standard numbers together just like you would do in basic math to get a grand total.
  4. Convert that grand total back into a sequence of ones and zeros by repeatedly checking which powers of two fit into the total.
  5. Write down the final sequence of ones and zeros as the answer.

Code Implementation

def add_binary(first_binary_string, second_binary_string):
    # Convert binary strings to base 10 integers because direct addition is easier in standard math
    decimal_value_one = int(first_binary_string, 2)
    
    decimal_value_two = int(second_binary_string, 2)
    
    # Add the standard decimal values together to find the combined total before converting back
    combined_total = decimal_value_one + decimal_value_two
    
    if combined_total == 0:
        return "0"
    
    binary_digit_list = []
    
    # Repeatedly divide by two and record remainders to reconstruct the binary sequence format
    while combined_total > 0:
        remainder_value = combined_total % 2
        
        binary_digit_list.append(str(remainder_value))
        
        combined_total = combined_total // 2
    
    binary_digit_list.reverse()
    
    final_binary_output = "".join(binary_digit_list)
    
    return final_binary_output

Big(O) Analysis

Time Complexity
O(n) – Letting n represent the maximum length of the two binary strings, the cost is driven by converting the sequences to standard numbers and back. The conversion steps visit each character in the strings a constant number of times. The intermediate arithmetic operations scale linearly with the magnitude of the values, which is bounded by the number of bits. Thus, the total operations approximate linear scaling with respect to the input length n, simplifying to O(n).
Space Complexity
O(N) – The brute force approach requires converting the binary sequences into standard everyday numbers, adding them, and then converting the grand total back into a new sequence of ones and zeros. Storing this final output sequence requires a character or string buffer that grows proportionally to the maximum length of the input sequences. If we define N as the maximum length of the two input binary strings, the resulting output sequence will take up O(N) auxiliary space. Therefore, the extra memory consumed by the algorithm scales linearly with the input size N.

Optimal Solution

Approach

To add two binary numbers together, the optimal approach mimics the way humans add numbers on paper by working from right to left. It pairs up corresponding digits, adds them together along with any carry over from the previous column, and builds the final result in reverse.

Here's how the algorithm would work step-by-step:

  1. Line up the two binary numbers so that their final digits match up on the right side.
  2. Begin at the very rightmost pair of digits and prepare to keep track of any overflow.
  3. Add the two digits together along with any overflow carried over from the previous step.
  4. Determine the new single digit result and whether there is a new overflow to pass along to the next column to the left.
  5. Write down the resulting digit as part of your final answer.
  6. Shift one position to the left to look at the next pair of digits and repeat the addition process.
  7. Continue moving left until you run out of digits in both numbers and have no remaining overflow left to process.
  8. Reverse the order of your written digits so that the final combined binary number reads correctly from left to right.

Code Implementation

def add_binary(first_binary_string, second_binary_string):
    pointer_first = len(first_binary_string) - 1
    pointer_second = len(second_binary_string) - 1
    carry_value = 0
    result_digits = []

    # Iterate backwards to process binary digits from right to left, aligning them correctly.
    while pointer_first >= 0 or pointer_second >= 0 or carry_value:
        current_sum = carry_value

        if pointer_first >= 0:
            current_sum += int(first_binary_string[pointer_first])
            pointer_first -= 1

        if pointer_second >= 0:
            current_sum += int(second_binary_string[pointer_second])
            pointer_second -= 1

        # Compute the current binary digit and update the carry for the next column position.
        carry_value = current_sum // 2
        result_digits.append(str(current_sum % 2))

    # Reverse the accumulated digits because the addition process built the result backwards.
    return "".join(result_digits[::-1])

Big(O) Analysis

Time Complexity
O(max(n, m)) – The time complexity is driven by a single traversal moving from the rightmost digits to the left of both binary strings. In each step of this traversal, we perform constant time arithmetic operations on the current pair of digits and the carry value. The loop runs a number of times equal to the length of the longer binary string, let us call it max(n, m). Since we process each digit position exactly once, the total operations scale linearly with the maximum input length, simplifying to O(max(n, m)).
Space Complexity
O(max(N, M)) – To store the intermediate results and the final combined binary number, the algorithm uses a string builder that grows proportionally to the length of the longer input string. Letting N represent the length of the first binary string and M represent the length of the second binary string, the output string requires a maximum of max(N, M) + 1 characters to account for a potential final carry. A few primitive integer variables are also used for pointers and the carry value, which require constant extra memory. Therefore, the total auxiliary space complexity is driven entirely by the output storage and simplifies to Big O of max(N, M).

Edge Cases

Strings of unequal length
How to Handle:
The loop continues by treating the missing digits of the shorter string as zero until both pointers and the carry are exhausted.
A final carry remaining after the longest string is fully processed
How to Handle:
An extra conditional check after the main loop ensures the final carry of 1 is prepended to the result.
Inputs containing multiple leading zeros such as 000 and 01
How to Handle:
The arithmetic pointer traversal correctly processes these zeros and outputs the minimal valid binary representation without unnecessary leading zeros.
Inputs consisting entirely of zeros such as 0 and 0
How to Handle:
The algorithm processes the single zero digits, results in a carry of zero, and correctly returns 0.
Maximum-sized inputs with thousands of binary digits
How to Handle:
Using string builders or dynamic character appending ensures linear time complexity and avoids quadratic string concatenation penalties.
Language-specific integer overflow on massive inputs
How to Handle:
Processing the inputs character by character avoids parsing them into native integer types which would overflow for very long binary strings.
0/257 completed