Add Binary - Problem
Binary Addition Made Simple!
Given two binary strings
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:
This problem tests your understanding of string manipulation, carry arithmetic, and binary number systems.
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
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
✓ Linear Growth
Space Complexity
O(max(n, m))
Result string length is at most max(n, m) + 1
⚡ 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?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code