Editorial
Core insight
Add Binary · String Manipulation Patterns
Core Insight for Add Binary
The core insight required to solve LeetCode 67 optimally is to recognize that computer addition (and elementary school column addition) works digit-by-digit from the least significant bit (right) to the most significant bit (left).
Since we cannot convert the entire string to a number, we must process the "numbers" index by index. The fundamental operation at any index involves three inputs:
- The bit from string
aat the current position (if available). - The bit from string
bat the current position (if available). - The
carryfrom the previous position (the right neighbor).
Visual Description:
Imagine aligning the two strings a and b at their rightmost characters. We place a pointer at the end of a and a pointer at the end of b. We also maintain a conceptual "carry" column. At each step, we sum the values pointed to by the pointers plus the current carry.
- If the sum is
0(binary0), the result bit is0, carry is0. - If the sum is
1(binary1), the result bit is1, carry is0. - If the sum is
2(binary10), the result bit is0, carry is1. - If the sum is
3(binary11), the result bit is1, carry is1.
This visualization confirms that we can build the result string in a single pass without ever converting the full string to an integer.
Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 67: Add Binary Solution & Explanation
Problem Overview
TL;DR: The optimal solution simulates bitwise addition from right to left using two pointers and a carry variable, treating the strings as arrays of digits.
The Add Binary problem asks us to take two non-empty binary strings, a and b, and return their summation as a binary string. Instead of interpreting these strings as standard integers—which could easily overflow standard data types given the constraints—we must perform the addition logically, character by character.
This is a classic "LeetCode 67" problem often used in interviews to test a candidate's ability to handle string manipulation and elementary arithmetic logic without relying on built-in big integer libraries.
Brute Force Approach for Add Binary
The most intuitive approach for a beginner might be to convert the binary strings into integer types, perform the addition, and then convert the result back into a binary string.
Naive Algorithm
- Parse string
ainto an integer (base 2). - Parse string
binto an integer (base 2). - Compute
sum = int_a + int_b. - Convert
sumback to a binary string representation.
Pseudo-code
function addBinary(a, b):
num1 = parseBinary(a)
num2 = parseBinary(b)
total = num1 + num2
return toBinaryString(total)Why this Fails
While this approach is logically sound for small inputs, it fails due to Integer Overflow in strictly typed languages like C++ or Java.
The problem constraints state that the length of the strings can be up to . A standard 64-bit integer (long long in C++ or long in Java) can only store values up to . A binary string of length represents a number roughly equal to , which is exponentially larger than what standard CPU registers can hold.
Although Python handles arbitrarily large integers automatically, relying on this feature defeats the purpose of the algorithmic interview question, which is to implement the addition logic manually.
Algorithm Strategy: Array - Plus One (Handling Carry)
The strategy strictly follows the "Handling Carry" subpattern:
- Initialization: Create two pointers,
iandj, pointing to the last characters of stringsaandbrespectively. Initialize an integercarryto 0. Use a mutable string builder (or dynamic array) to construct the result. - Iteration: Loop as long as either pointer is valid (non-negative) OR
carryis non-zero. This ensures we process all digits and don't drop a final carry (e.g., ). - Digit Extraction: inside the loop, extract the numeric value of the current characters. If a pointer has moved past the beginning of the string (index < 0), treat the value as
0. - Computation:
- Calculate
sum = digit_a + digit_b + carry. - Determine the current result bit:
sum % 2. - Determine the new carry:
sum / 2(integer division).
- Calculate
- Construction: Append the result bit to our builder.
- Finalization: Since we appended bits from least significant to most significant (right to left), the result string is currently backwards. Reverse the string to obtain the final correct binary representation.
Execution Flow
Let's trace a = "11", b = "1".
- Start:
i = 1(points to last '1' in "11"),j = 0(points to '1'),carry = 0. - Iteration 1:
val_a= 1,val_b= 1.total= 1 + 1 + 0 = 2.bit= 2 % 2 = 0. Append "0".carry= 2 / 2 = 1.- Decrement
ito 0,jto -1.
- Iteration 2:
val_a= 1 (at index 0),val_b= 0 (index out of bounds).total= 1 + 0 + 1 (carry) = 2.bit= 2 % 2 = 0. Append "0". Result is now "00".carry= 2 / 2 = 1.- Decrement
ito -1,jto -2.
- Iteration 3:
- Pointers are invalid, but loop continues because
carry(1) > 0. val_a= 0,val_b= 0.total= 0 + 0 + 1 = 1.bit= 1 % 2 = 1. Append "1". Result is now "001".carry= 1 / 2 = 0.
- Pointers are invalid, but loop continues because
- End: Loop terminates.
- Reverse: "001" becomes "100".
Proof of Correctness
The correctness of this algorithm relies on the mathematical properties of addition in positional numeral systems.
- Invariant: At any step (processing the -th bit from the right), the computed bit is strictly , and the carry passed to step is . This matches the definition of binary addition.
- Termination: The loop processes every bit of the longer string exactly once. The condition
carry > 0ensures that if the most significant bits sum to a value , the resulting overflow creates a new most significant bit (MSB), preventing data loss. - Boundary Handling: By treating out-of-bounds indices as 0, we effectively pad the shorter string with leading zeros without allocating extra memory, preserving the numeric value.
Pattern Reuse Notes
The Array - Plus One (Handling Carry) pattern is fundamental for arbitrary-precision arithmetic. You can apply this exact logic to:
- LeetCode 66: Plus One: Similar logic, but you are only adding
1to a single array of digits representing a number. - LeetCode 43: Multiply Strings: Multiplication is essentially repeated addition with shifts; managing the carry is the central component of the inner loop.
- LeetCode 989: Add to Array-Form of Integer: Identical to Add Binary, but in base-10 using an array and an integer.
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 67
1class Solution {
2public:
3 string addBinary(string a, string b) {
4 string result = "";
5 int i = a.length() - 1;
6 int j = b.length() - 1;
7 int carry = 0;
8
9 // Iterate as long as we have digits or a remaining carry
10 while (i >= 0 || j >= 0 || carry > 0) {
11 int sum = carry;
12
13 // Add digit from a if available
14 if (i >= 0) {
15 sum += a[i] - '0'; // Convert char to int
16 i--;
17 }
18
19 // Add digit from b if available
20 if (j >= 0) {
21 sum += b[j] - '0'; // Convert char to int
22 j--;
23 }
24
25 // sum % 2 is the current digit, sum / 2 is the carry
26 result += to_string(sum % 2);
27 carry = sum / 2;
28 }
29
30 // The result was built backwards, so reverse it
31 reverse(result.begin(), result.end());
32 return result;
33 }
34};Java Solution for LeetCode 67
1class Solution {
2 public String addBinary(String a, String b) {
3 StringBuilder sb = new StringBuilder();
4 int i = a.length() - 1;
5 int j = b.length() - 1;
6 int carry = 0;
7
8 // Iterate backwards through both strings
9 while (i >= 0 || j >= 0 || carry > 0) {
10 int sum = carry;
11
12 if (i >= 0) {
13 sum += a.charAt(i) - '0'; // Convert char to int
14 i--;
15 }
16 if (j >= 0) {
17 sum += b.charAt(j) - '0'; // Convert char to int
18 j--;
19 }
20
21 // Append current bit (remainder)
22 sb.append(sum % 2);
23 // Update carry (quotient)
24 carry = sum / 2;
25 }
26
27 // Reverse to get the correct order
28 return sb.reverse().toString();
29 }
30}Python Solution for LeetCode 67
1class Solution:
2 def addBinary(self, a: str, b: str) -> str:
3 res = []
4 i, j = len(a) - 1, len(b) - 1
5 carry = 0
6
7 # Process both strings from right to left
8 while i >= 0 or j >= 0 or carry:
9 total = carry
10
11 if i >= 0:
12 total += int(a[i])
13 i -= 1
14 if j >= 0:
15 total += int(b[j])
16 j -= 1
17
18 # Append the least significant bit of total
19 res.append(str(total % 2))
20 # Update carry
21 carry = total // 2
22
23 # Reverse the list and join to form the string
24 return "".join(res[::-1])