← Questions
Add two binary strings
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Jan 2026. It tests strings and math.
Given two binary numbers as strings, return their sum as a binary string. The inputs can be far longer than any built-in integer type, so add them digit by digit with a carry instead of converting them to integers.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
add_binary(a: str, b: str) -> str—aandbcontain only0and1, with no leading zeros except the number"0"itself.
Example
add_binary("11", "1") -> "100"
add_binary("1010", "1011") -> "10101"
add_binary("0", "0") -> "0"
add_binary("1", "111") -> "1000"
Constraints
-
1 <= len(a), len(b) <= 10^4(assume they may be much longer in the discussion). - No leading zeros except for
"0".
Clarifying questions
- Can inputs have leading zeros, and should the output strip them?
- Can either string be empty?
- Is converting to an integer allowed? (Here it is not.)
What a strong answer covers
- Two indices from the right end of each string and a carry; each step adds the two digits and the carry, appends
sum % 2, and keepssum // 2as the carry. - Continuing while either index is valid or the carry is 1, so the final carry is not lost.
- Building the result in a list and reversing once, rather than prepending to a string.
-
O(max(len(a), len(b)))time and space. - Tests: different lengths, a carry that ripples through every digit (
"1111" + "1"), both inputs"0".
Follow-ups
- Add numbers in any base from 2 to 36.
- Subtract or multiply two binary strings.
- Add two very long numbers given as linked lists of digits, most significant first.
Where it's asked
- Meta · AI-enabled coding · Last asked Jan 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
