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 <= 104a and b consist only of '0' or '1' characters.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:
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:
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_outputTo 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:
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])| Case | How to Handle |
|---|---|
| Strings of unequal length | 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 | 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 | 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 | 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 | Using string builders or dynamic character appending ensures linear time complexity and avoids quadratic string concatenation penalties. |
| Language-specific integer overflow on massive inputs | Processing the inputs character by character avoids parsing them into native integer types which would overflow for very long binary strings. |