Add Binary
LeetCode 67 | Difficulty: Easyβ
EasyProblem Descriptionβ
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 <= 10^4`
- `a` and `b` consist only of `'0'` or `'1'` characters.
- Each string does not contain leading zeros except for the zero itself.
Topics: Math, String, Bit Manipulation, Simulation
Approachβ
Bit Manipulationβ
Operate directly on binary representations. Key operations: AND (&), OR (|), XOR (^), NOT (~), shifts (<<, >>). XOR is especially useful: a ^ a = 0, a ^ 0 = a.
Finding unique elements, power of 2 checks, subset generation, toggling flags.
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
Problems with clear mathematical structure, counting, number properties.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 96 ms)β
| Metric | Value |
|---|---|
| Runtime | 96 ms |
| Memory | N/A |
| Date | 2018-03-25 |
public class Solution {
public string AddBinary(string a, string b) {
int m = a.Length-1;
int n = b.Length-1;
int carry = 0;
string result = "";
while(m>=0 || n>=0)
{
int sum = carry;
if(m>=0)
{
sum += a[m]-'0';
m--;
}
if(n>=0)
{
sum+=b[n]-'0';
n--;
}
result = sum%2 + result;
carry = sum/2;
}
if(carry>0) result = carry.ToString() + result;
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Bit Manipulation | $O(n) or O(1)$ | $O(1)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.