Skip to main content

Add Binary

LeetCode 67 | Difficulty: Easy​

Easy

Problem 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.

When to use

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.

When to use

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.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 96 ms)​

MetricValue
Runtime96 ms
MemoryN/A
Date2018-03-25
Solution
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​

ApproachTimeSpace
Bit Manipulation$O(n) or O(1)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.