Add Binary — LeetCode 67 Python Solution

EasyBit ManipulationMathStringSimulation
Problem
#67
Reading time
2 min

The problem

Given two binary strings a and b, return their sum as a binary string.

Example

Input
a = "11", b = "1"
Output
"100"

Python solution

Python
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        ans = []
        i, j, carry = len(a) - 1, len(b) - 1, 0
        while i >= 0 or j >= 0 or carry:
            carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j]))
            carry, v = divmod(carry, 2)
            ans.append(str(v))
            i, j = i - 1, j - 1
        return "".join(ans[::-1])

Complexity

MeasureComplexity
TimeO(\max(m, n)), where m and n are the lengths of strings a and b respectively
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 67. Add Binary is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On study lists

This problem is on Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 67. Add Binary?
LeetCode 67. Add Binary is rated Easy on LeetCode.
What is the time complexity of LeetCode 67. Add Binary?
The Python solution on this page runs in O(\max(m, n)), where m and n are the lengths of strings a and b respectively.
What is the space complexity of LeetCode 67. Add Binary?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 67. Add Binary cover?
LeetCode 67. Add Binary is tagged Bit Manipulation, Math, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview