Add Binary - Problem
Binary Addition Made Simple!

Given two binary strings a and b, your task is to return their sum as a binary string. This is essentially performing addition in base-2 (binary) instead of our usual base-10 (decimal) system.

What you need to know:
• Binary uses only digits 0 and 1
• Addition rules: 0+0=0, 0+1=1, 1+0=1, 1+1=10 (carry the 1)
• Work from right to left, just like decimal addition

Example: "1010" + "1011" = "10101"

This problem tests your understanding of string manipulation, carry arithmetic, and binary number systems.

Input & Output

example_1.py — Basic Addition
$ Input: a = "11", b = "1"
Output: "100"
💡 Note: 11 + 1 = 100 in binary (equivalent to 3 + 1 = 4 in decimal)
example_2.py — Equal Length Strings
$ Input: a = "1010", b = "1011"
Output: "10101"
💡 Note: 1010 + 1011 = 10101 in binary (equivalent to 10 + 11 = 21 in decimal)
example_3.py — Single Digits
$ Input: a = "1", b = "1"
Output: "10"
💡 Note: 1 + 1 = 10 in binary (equivalent to 1 + 1 = 2 in decimal) - demonstrates carry

Visualization

Tap to expand
Binary Addition VisualizationExample: 1101 + 1010 = 10111Step 1: Rightmost position11011010a:b:1+0=1Step 2-4: Continue with carries10111Result:Carry Operations:Position 0: 1 + 0 = 1Position 1: 0 + 1 = 1Position 2: 1 + 0 = 1Position 3: 1 + 1 = 10→ digit=0, carry=1Position 4: 0 + 0 + carry(1) = 1Binary Addition Rules:• 0 + 0 = 0• 0 + 1 = 1• 1 + 0 = 1• 1 + 1 = 10 (write 0, carry 1)
Understanding the Visualization
1
Start from Right
Begin with the rightmost digits of both strings
2
Add with Carry
Add current digits plus any carry from previous step
3
Handle Overflow
If sum ≥ 2, write (sum%2) and carry (sum/2)
4
Move Left
Continue until all digits processed and no carry remains
Key Takeaway
🎯 Key Insight: Binary addition works exactly like decimal addition - process digits right to left with carry, but using only 0s and 1s!

Time & Space Complexity

Time Complexity
⏱️
O(max(n, m))

We process each digit exactly once, where n and m are lengths of input strings

n
2n
Linear Growth
Space Complexity
O(max(n, m))

Result string length is at most max(n, m) + 1

n
2n
Linearithmic Space

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
  • Follow up: How would you handle this if you cannot use built-in big integer libraries?
Asked in
Meta 35 Amazon 28 Google 22 Microsoft 18
38.2K Views
High Frequency
~18 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen