easy Add Binary
Problem Statement
Given two binary strings a and b, return a sum of a and b represented as binary strings.
Examples
-
Example 1:
- Input: a = "10110", b = "10101"
- Expected Output: "101011"
- Justification: The binary sum of "10110" (22 in decimal) and "10101" (21 in decimal) is "101011" (43 in decimal).
-
Example 2:
- Input: a = "111", b = "1"
- Expected Output: "1000"
- Justification: The binary sum of "111" (7 in decimal) and "1" (1 in decimal) is "1000" (8 in decimal).
-
Example 3:
- Input: a = "0", b = "0"
- Expected Output: "0"
- Justification: The binary sum of "0" and "0" remains "0".
Try it yourself
Try solving this question here:
🎯 STRICT STANDOUT — Add Binary easy
0. Why / judgment (K3)
Family: Simulation / digit DP-lite · two indices + carry
Signal: two numbers as strings in base 2 + produce sum string. Converting to int fails on length (up to 10^4). The standout move is simulate grade-school addition from the right with a carry — same mental model as Add Strings / Plus One chain.
1. Pattern + recognition + when-NOT (K12)
Pattern / template: Template: i=|a|-1, j=|b|-1, carry=0; while i≥0 or j≥0 or carry: sum bits + carry; append sum%2; carry=sum//2; reverse result. Recognition: multi-digit arithmetic on strings / arrays from LSB.
When-NOT: Not two-pointers on characters for equality. Not stack. Not DP. If inputs fit native int and language allows bigints freely, convert — but interviews want the simulation. If bases differ or digits need arbitrary precision multiply → different algorithms.
2. Complexity derivation (K11)
Let n=|a|, m=|b|.
Loop runs max(n,m)+1 times (final carry) → Θ(max(n,m)).
Each step O(1) arithmetic on bits 0/1.
Space Θ(max(n,m)) for output (or builder + reverse).
Cannot do better asymptotically: output length is Θ(max(n,m)).
3. Edge hand-run (K13)
a="0", b="0" → "0" (not "00").
a="1", b="111" → walk: 1+1→0 c1; 0+1+1→0 c1; 0+1+1→0 c1; carry1 → "1000".
Unequal lengths: exhausted side contributes 0.
All 1s same length: result length n+1.
4. Interviewer follow-ups & drills
Q1. Why not Integer.parseInt(a,2)+…?
Model answer: Overflow / length limits; interview wants O(n) digit sim.
Q2. Where does the extra bit come from?
Model answer: Final carry after MSB — output may be max+1 long.
Q3. Same pattern as?
Model answer: Add Strings, plus-one on digit array, linked-list add two numbers.
✅ Solution Add Binary
Problem Statement
Given two binary strings a and b, return a sum of a and b represented as binary strings.
Examples
-
Example 1:
- Input: a = "10110", b = "10101"
- Expected Output: "101011"
- Justification: The binary sum of "10110" (22 in decimal) and "10101" (21 in decimal) is "101011" (43 in decimal).
-
Example 2:
- Input: a = "111", b = "1"
- Expected Output: "1000"
- Justification: The binary sum of "111" (7 in decimal) and "1" (1 in decimal) is "1000" (8 in decimal).
-
Example 3:
- Input: a = "0", b = "0"
- Expected Output: "0"
- Justification: The binary sum of "0" and "0" remains "0".
Solution
To solve this problem, we'll iterate over the input strings from right to left, simulating the binary addition process. We choose this approach because it directly simulates how binary addition works, carrying over bits when necessary. Our solution needs to handle different lengths of binary strings and the carry that can occur after adding the last bits.
By processing the strings from the end towards the beginning, we can easily manage carries and ensure that we consider all bits in both strings. If one string is shorter, we'll treat missing bits as '0'. This method is effective because it mirrors manual binary addition, ensuring no bit is missed and carries are correctly applied, resulting in an accurate binary sum.
Step-by-Step Algorithm
-
Initialize Variables:
- Create a variable
resultto store the final binary sum as a string. - Initialize two index variables,
iandj, to point to the last characters of stringsaandbrespectively. - Initialize a
carryvariable to 0, which will hold the carry-over value when adding two binary digits.
- Create a variable
-
Iterate Over Strings:
- Use a loop to iterate while either
iorjis non-negative, orcarryis 1. This ensures that you continue addition until both strings are completely traversed and any remaining carry is processed.
- Use a loop to iterate while either
-
Calculate Sum:
- Within the loop, for each position starting from the end, add the corresponding binary digits of
aandb, along with thecarry. - If
iorjhas gone negative (indicating one string is shorter), treat the missing digits as 0.
- Within the loop, for each position starting from the end, add the corresponding binary digits of
-
Update Result and Carry:
- Calculate the binary digit to be appended to the result (
sum % 2) and update thecarry(sum / 2). - Prepend the calculated digit to the
resultstring.
- Calculate the binary digit to be appended to the result (
-
Handle Remaining Carry:
- After the loop, if there's a remaining
carry, prepend it to theresult.
- After the loop, if there's a remaining
-
Return the Result:
- Return the
resultstring, which now contains the binary sum ofaandb.
- Return the
Algorithm Walkthrough
Let's consider the input: a = "10110", b = "10101"
-
Initialization:
result= ""i= 4 (pointing to the last character of "10110")j= 4 (pointing to the last character of "10101")carry= 0
-
First Iteration (rightmost digits):
a[i] = 0,b[j] = 1sum = 0 + 1 + 0 (carry) = 1result= sum%2 + result = 1%2 + "" = "1",carry= sum/2 = 1/2 = 0i= 3,j= 3
-
Second Iteration:
a[i] = 1,b[j] = 0sum = 1 + 0 + 0 = 1result= sum%2 + result = 1%2 + "1" ="11",carry= sum/2 = 1/2 = 0i= 2,j= 2
-
Third Iteration:
a[i] = 1,b[j] = 1sum = 1 + 1 + 0 = 2result= sum%2 + result = 2%2 + "11" = "011",carry= sum/2 = 2/2 = 1i= 1,j= 1
-
Fourth Iteration:
a[i] = 0,b[j] = 0sum = 0 + 0 + 1 (carry) = 1result= sum%2 + result = 1%2 + "011" = "1011",carry= sum/2 = 1/2 = 0i= 0,j= 0
-
Fifth Iteration:
a[i] = 1,b[j] = 1sum = 1 + 1 + 0 = 2result= sum%2 + result = 2%2 + "1011" = "01011",carry= sum/2 = 2/2 = 1i= -1,j= -1
-
Handle Remaining Carry:
- Since
carry= 1,result= "101011"
- Since
-
Final Result:
- The final binary sum is "101011", which is the correct sum of "10110" and "10101".
Code
public class Solution {
// Method to add two binary strings without needing to reverse at the end
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
// Loop through both strings from end to start
while (i >= 0 || j >= 0 || carry == 1) {
int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0'; // Add bit from a
if (j >= 0) sum += b.charAt(j--) - '0'; // Add bit from b
// Prepend the calculated bit to the result string
result.insert(0, sum % 2); // Use insert to prepend
carry = sum / 2; // Determine new carry
}
return result.toString(); // No need to reverse
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test the examples
System.out.println(sol.addBinary("10110", "10101")); // "101011"
System.out.println(sol.addBinary("111", "1")); // "1000"
System.out.println(sol.addBinary("0", "0")); // "0"
}
}
Complexity Analysis
Time Complexity
Space Complexity
max(N, M) + 1 (due to a possible carry that adds an extra digit).
🎯 STRICT STANDOUT — Solution Add Binary
0. Why / judgment (K3)
Family: Simulation / digit arithmetic + carry
Solution pages must lock the invariant: after processing position k from the right, result holds the correct lower bits and carry is the only unfinished state. Building left-to-right forces knowing lengths first; right-to-left is simpler and less error-prone. Reverse (or prepend deque) at end — O(n) still.
1. Pattern + recognition + when-NOT (K12)
Pattern / template: while i≥0 or j≥0 or carry: bitA = a[i--] if i≥0 else 0; same for b; s=bitA+bitB+carry; append s&1; carry=s>>1. Recognition: string-coded numbers, base b digit sum.
When-NOT: Do not map to stack matching or two-sum. Do not use recursion on substrings (stack depth). Do not claim O(1) space if you allocate the full answer string — answer is Ω(n).
2. Complexity derivation (K11)
Time: one pass max(n,m)+1 → O(n+m).
Space: O(n+m) output; O(1) extra besides output if reverse in place builder.
If using immutable string concat naively in a loop: accidental O((n+m)²) — avoid.
3. Edge hand-run (K13)
Hand-run a="11", b="1":
i=1,j=0,c=0: 1+1+0=2 → bit0 c1
i=0,j=-1,c=1: 1+0+1=2 → bit0 c1
i=-1,c=1: 0+0+1=1 → bit1 c0 → reverse "100".
Edge: leading zeros in input? Treat as part of value; output usually without padding except "0".
4. Interviewer follow-ups & drills
Q1. Prove no off-by-one on unequal length
Model answer: Missing side contributes 0 until both indices and carry done.
Q2. Why reverse at end?
Model answer: We append LSB first; reverse restores MSB-left convention.
Q3. Hostile: carry only case?
Model answer: a="1"*k, b="1" → may ripple all the way; still O(k).
Recognize it: Scan once tracking what you need (running max/sum), or precompute a prefix-sum / hash → turn O(n²) into O(n).
▶ Visualize this problem (step it, predict each fork)
🤖 Don't fully get this? Learn it with Claude
Stuck on Add Binary? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Add Binary** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Add Binary** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Add Binary**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Add Binary**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.