InterviewPrepKit

Home / Coding / Bit Manipulation

Add Binary

easy Original β†—
Solving tips
  • Simulate grade-school addition: walk both strings from the right with a carry, at each column total = carry + bitA + bitB, output bit is total & 1 and next carry is total >> 1.
  • Guard each index independently (if i>=0) since the strings can differ in length, and keep looping while either index is valid OR carry is nonzero.
  • Target O(n) time and O(n) space (n = max length); build the answer least-significant-first, so reverse before joining.
  • Pitfalls: dropping the final carry (loses leading 1), and the pure XOR/AND fold (answer=x^y, carry=(x&y)<<1) is conceptually elegant but O(n^2) bit ops due to rippling carries.

Problem

You are given two non-negative integers written as binary strings a and b. Return their sum, also as a binary string. Neither input has leading zeros (except the string "0" itself), and your output should follow the same rule. The two strings may have different lengths.

Examples

  • a = "11", b = "1" β†’ "100" β€” 3 + 1 = 4, which is 100 in binary.
  • a = "1010", b = "1011" β†’ "10101" β€” 10 + 11 = 21.
  • a = "0", b = "0" β†’ "0" β€” nothing to carry.

Constraints

  • 1 <= a.length, b.length <= 10^4
  • Each string consists only of '0' and '1', with no leading zeros beyond a lone "0".

Lengths up to 10^4 mean the sum can be ~10^4 bits wide. Python’s big integers swallow that, but the interview point is to add correctly without leaning on a fixed-width integer type that would overflow.

Think about it first

Hint 1 Think grade-school addition: line the strings up at the right end and add column by column, carrying a `1` whenever a column sums to 2 or 3.
Hint 2 On bits, `x ^ y` is exactly "add without carrying," and `x & y` marks the columns where a carry is *born*. Shift that carry left by one to move it into the next column.
Hint 3 Keep folding: `answer = x ^ y`, `carry = (x & y) << 1`, then repeat with those two until the carry is `0`. What is left in `x` is the sum.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.