Add Binary — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Given two binary strings, return their sum as a binary string.” You know the algorithm: simulate digit-by-digit addition from right to left, maintaining a carry. But the implementation details trip people up: carry handling, unequal-length strings, and how to traverse from the end without reversing. This is LeetCode #67, and getting every edge case right on the first try is what separates a clean solve from a messy one.
This walkthrough covers the pointer-based simulation approach, the Pythonic shortcut, and the common traps candidates fall into.
The Problem
Given two binary strings a and b, return their sum as a binary string. (LeetCode #67)
Example 1
Input: a = "11", b = "1"
Output: "100"
Example 2
Input: a = "1010", b = "1011"
Output: "10101"
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Right-to-left pointer traversal | Do you use indices from the end instead of reversing? |
| Carry propagation | Do you handle the final carry after the loop? |
| Unequal length strings | Does your code handle strings of different lengths correctly? |
| String building | Do you use a list and join at the end instead of string concatenation? |
Step 1: Clarifying Questions
1. Can the strings be empty? Assume at least one character per constraints.
2. Leading zeros in input? Problem guarantees no leading zeros (except “0” itself).
3. Should the output have leading zeros? No. Match standard binary representation.
Step 2: A First (Non-Optimal) Idea
Convert both binary strings to integers, add them, and convert back to binary. This works, but interviewers typically want the simulation approach since it demonstrates low-level addition mechanics.
| Approach | Time | Space |
|---|---|---|
| Simulation | O(max(m, n)) | O(max(m, n)) |
| Python built-ins | O(max(m, n)) | O(max(m, n)) |
Step 3: The Key Insight
Simulate binary addition right-to-left, maintaining a carry. Use two pointers starting from the end of each string (no reversal needed). At each step:
digit_sum = a[i] + b[j] + carry. The result bit isdigit_sum % 2, and the new carry isdigit_sum // 2. After the loop, handle any remaining carry.
---
Step 4: Algorithm
- Initialize two pointers
iandjat the ends ofaandb. - Initialize
carry = 0and a result list. - While either pointer is valid or carry is non-zero:
- Add
a[i],b[j](if valid), and carry. - Append
digit_sum % 2to result. - Update carry to
digit_sum // 2.
- Add
- Reverse and join the result list.
Python Implementation
Simulation approach:
def addBinary(a: str, b: str) -> str:
i, j = len(a) - 1, len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry:
digit_sum = carry
if i >= 0:
digit_sum += int(a[i])
i -= 1
if j >= 0:
digit_sum += int(b[j])
j -= 1
result.append(str(digit_sum % 2)) # Current bit
carry = digit_sum // 2 # New carry
return ''.join(reversed(result))
Pythonic shortcut (acceptable, but discuss trade-offs):
def addBinary(a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
int(a, 2) converts a binary string to an integer, bin() converts back, and [2:] strips the "0b" prefix. Clean but uses built-in conversion. Ask the interviewer if this is acceptable.
Time and Space Complexity
| Aspect | Complexity |
|---|---|
| Time | O(max(m, n)) |
| Space | O(max(m, n)), for the result list |
Common Interview Mistakes
-
Using
+to build a string in a loop. String concatenation in a loop is O(n²) in Python. Use a list and join at the end. -
Forgetting the final carry. If both strings are exhausted but
carry == 1, you must append it. Theor carrycondition in the while loop handles this. -
Reversing the input strings. You can traverse from the end using indices. No need to reverse.
-
Not mentioning the built-in approach. Show both and let the interviewer decide. If they want the simulation, the built-in shows you know the language.
What a Strong Candidate Sounds Like
“I’ll simulate binary addition right-to-left with two pointers and a carry variable. At each step,
digit_sum = a[i] + b[j] + carry. The result bit isdigit_sum % 2, carry isdigit_sum // 2. I continue while either index is valid or carry is nonzero. I collect digits in a list (not string concatenation, to avoid O(n²) cost), then join and reverse. There’s also a Pythonic one-liner usingint(a, 2)andbin()if built-ins are acceptable.”
Example Interview Dialogue
Interviewer: What happens when the strings have different lengths?
Candidate: The while loop condition uses or, so it continues as long as at least one pointer is valid. When a shorter string is exhausted, only the other string’s digits are added to the carry. This naturally handles unequal lengths without special cases.
Related Problems to Practice
- Add Strings (LeetCode #415). Same pattern for decimal strings.
- Multiply Strings (LeetCode #43). Multiplication without converting to int.
- Sum of Two Integers (LeetCode #371). Binary addition using bit manipulation.
From the Intervu walkthrough collection:
- Two Sum — Digit/value addition fundamentals.
- Climbing Stairs — Step-by-step state building.
- Valid Palindrome — String traversal with two pointers.
Practice This in a Mock Interview
Add Binary is fast to code but exposes sloppy habits like string concatenation in loops and forgotten carry bits. A clean, bug-free first attempt is what interviewers are looking for.
Start a mock interview for Add Binary on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap and study plans
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub, condensed solutions with code