Problem 67

Abstract / Summary

Add two binary strings and return their sum as a binary string without using built in conversion functions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0067.cpp

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());

        while (a.size() < b.size())
            a += '0';
        while (b.size() < a.size())
            b += '0';

        string result;
        result.reserve(a.size() + 1);

        int carry = 0;
        for (int i = 0; i < a.size(); i++)
        {
            int sum = carry + (a[i] - '0') + (b[i] - '0');

            result += '0' + (sum & 1);
            carry = sum >> 1;
        }

        if (carry > 0)
            result += '1';

        reverse(result.begin(), result.end());

        return result;
    }
};
31 lines | 700 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (4+ million submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Math
  • Simulation
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the binary sum of two strings representing non-negative binary numbers. It follows a classic approach of aligning the operands from the least significant bit, performing digit-wise addition with a carry, and finally producing the result in the correct order. The algorithm works entirely with standard library operations and avoids dynamic memory allocations beyond the reserved result buffer.

Key Steps

The first phase reverses both input strings so that indexβ€―0 corresponds to the least significant bit. This enables a straightforward left-to-right traversal during addition.

reverse(a.begin(), a.end());
reverse(b.begin(), b.end());

Next, the code equalizes the lengths of the two strings by appending '0' characters to the shorter one. This guarantees that the subsequent loop can safely access a[i] and b[i] for every index.

while (a.size() < b.size())
    a += '0';
while (b.size() < a.size())
    b += '0';

A result string is created and its capacity is pre-allocated to accommodate the maximum possible length, which is the length of the longer operand plus one extra character for a potential final carry.

string result;
result.reserve(a.size() + 1);

The core addition loop iterates over each position, computes the sum of the corresponding bits together with the current carry, extracts the resulting bit using a bitwise AND, and updates the carry with a right shift. The resulting bit is appended to the result string.

int carry = 0;
for (int i = 0; i < a.size(); i++)
{
    int sum = carry + (a[i] - '0') + (b[i] - '0');

    result += '0' + (sum & 1);
    carry = sum >> 1;
}

After processing all positions, a leftover carry is appended if it is non-zero, ensuring that overflow is correctly represented.

if (carry > 0)
    result += '1';

Finally, the result string, which has been built in reverse order, is reversed to present the binary number in the conventional most-significant-bit-first format.

reverse(result.begin(), result.end());
return result;

Edge Cases Handled

The algorithm gracefully manages inputs of differing lengths by padding the shorter string with '0' characters, thereby eliminating the need for conditional checks inside the addition loop. When both inputs consist solely of '0' characters, the loop produces a single '0' result, and the final carry check does not add an extra digit. If the addition generates an overflow beyond the original length-such as adding "1" and "1"-the explicit carry handling appends the leading '1', yielding the correct "10" result. The use of reserve ensures that even the maximal length case (original length plus one) is accommodated without reallocation.

Performance Optimizations

Reversing the input strings in place avoids the overhead of creating auxiliary reversed copies. Length equalization through simple concatenation of '0' characters is performed only once per string, preventing repeated size checks during the main loop. Pre-allocating the result buffer with reserve eliminates incremental memory allocations as characters are appended, which can be costly in tight loops. The addition logic leverages bitwise operations (& 1 and >> 1) to extract the result bit and compute the new carry efficiently, avoiding more expensive arithmetic or conditional branching. By operating directly on character codes (a[i] - '0'), the code sidesteps the need for conversion functions, further reducing runtime overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two towers made of blocks, where each block is either a zero or a one. To add the towers together, the code first flips them over so the bottom blocks are at the very top. This makes it easier to start counting from the bottom of each pile up to the top. Because the towers might have different heights, the code fills in the shorter tower with extra zero blocks until both piles look like they are exactly the same size. Now, it looks at each pair of blocks and adds them together. If two ones are added, they become a two, which is too big, so it turns into a zero and leaves a little extra block behind that needs to be carried over to the next pair. This process continues for every single block in the towers. If there is a leftover piece at the very end, it gets added as a final block. Once everything is done, the tower is flipped back over to its original position to show the final answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.96 | σ = 0.76

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
withaarzoo C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
withaarzoo C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
59 links | 43 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 67. Add Binary Solution Explained - Java'
Nick White 11 mins
LeetCode 67. Add Binary Solution Explained - Java
YouTube video 'Add Binary - Leetcode 67 - Bit Manipulation (Python)'
Greg Hogg 9 mins
Add Binary - Leetcode 67 - Bit Manipulation (Python)
YouTube video '67. Add Binary || Java || Leetcode || Hindi'
Coding Sphere 8 mins
67. Add Binary || Java || Leetcode || Hindi
YouTube video 'Add Binary | Simple Explanation | Dry Run | Leetcode 67 | codestorywithMIK'
codestorywithMIK 13 mins
Add Binary | Simple Explanation | Dry Run | Leetcode 67 | codestorywithMIK
YouTube video 'Add Binary LeetCode 67 | Intuitive Explanation + Code'
CodingNinja 10 mins
Add Binary LeetCode 67 | Intuitive Explanation + Code
YouTube video 'Add Binary | Leetcode - 67'
Algorithms Made Easy 5 mins
Add Binary | Leetcode - 67
YouTube video 'Add Binary | Leet code 67 | Theory explained + Python code | July Leet code challenge'
Sai Anish Malla 7 mins
Add Binary | Leet code 67 | Theory explained + Python code | July Leet code challenge
YouTube video '67. Add Binary | JavaScript | O(n) TC | O(1) SC | LeetCode Daily Challenge'
LeetCodeWithMonu 8 mins
67. Add Binary | JavaScript | O(n) TC | O(1) SC | LeetCode Daily Challenge
YouTube video 'add binary | add binary leetcode | leetcode 67 | bitwise | 1 liner'
Naresh Gupta 6 mins
add binary | add binary leetcode | leetcode 67 | bitwise | 1 liner
YouTube video 'Add Binary - LeetCode 67 - Coding Interview Questions'
One Code Man 6 mins
Add Binary - LeetCode 67 - Coding Interview Questions
YouTube video 'LeetCode 67 - Add Binary - JavaScript -  Solution'
LeadEngineer 15 mins
LeetCode 67 - Add Binary - JavaScript - Solution
YouTube video 'Leetcode 67 Add Binary (Java)'
TheAnalyticGuy 8 mins
Leetcode 67 Add Binary (Java)
YouTube video 'Add Binary | Leetcode 67  |  Live coding session πŸ”₯πŸ”₯πŸ”₯ |Easy Peasy  πŸ’―πŸ’―πŸ’―'
Coding Decoded 6 mins
Add Binary | Leetcode 67 | Live coding session πŸ”₯πŸ”₯πŸ”₯ |Easy Peasy πŸ’―πŸ’―πŸ’―
YouTube video 'Leetcode 67 - Add Binary (JAVA Solution Explained!)'
LC Bear 6 mins
Leetcode 67 - Add Binary (JAVA Solution Explained!)
YouTube video '67 ||  Add Binary II || C++ || Leetcode Daily Challenge'
CodeFreaks 9 mins
67 || Add Binary II || C++ || Leetcode Daily Challenge
YouTube video '67. Add Binary | Leetcode Daily - Python'
Leetcode Daily 9 mins
67. Add Binary | Leetcode Daily - Python
YouTube video 'πŸŽ₯ LeetCode 67: Add Binary | C++ Solution + Step-by-Step Explanation (Beats 100%)'
CodeWithBK 11 mins
πŸŽ₯ LeetCode 67: Add Binary | C++ Solution + Step-by-Step Explanation (Beats 100%)
YouTube video 'Add Binary | LeetCode 67 | Java Code | Developer Coder'
Developer Coder 10 mins
Add Binary | LeetCode 67 | Java Code | Developer Coder
YouTube video 'Daily Leetcode #1050: Feb 14, 2023 - 67. Add Binary'
Programming Live with Larry 6 mins
Daily Leetcode #1050: Feb 14, 2023 - 67. Add Binary
YouTube video 'Leetcode 67: Add Binary | Python Solution in Telugu | Two Pointers + Conversion | srkcodes'
Srk Codes 14 mins
Leetcode 67: Add Binary | Python Solution in Telugu | Two Pointers + Conversion | srkcodes
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality