LeetCode
LeetCode 67: Add Binary Solution in Python
A look at a concise Python solution to LeetCode’s Add Binary problem, demonstrating an efficient use of builtin functions to achieve binary addition in a single line of code.
In this tutorial article, I go through my Python solution to the Add Binary problem from LeetCode. My code uses Python’s builtin functions for binarydecimal conversion, which helps reduce the solution to a single return statement with only one line of code.
class Solution:
def addBinary(self, a: str, b: str):
# Remove the '0b' prefix from result.
return bin(int(a, 2) + int(b, 2))[2:]
Understanding the Logic
The code snippet provided defines a class named Solution
with a method addBinary
, designed to sum two binary numbers represented as strings. The method operates by first converting the input strings a
and b
into their decimal equivalents using the int
function with a base of 2, allowing for the interpretation of these strings as binary numbers.
Following this conversion, the method adds the two resulting decimal numbers together. To convert this sum back into a binary representation, the bin
function is employed, which yields a string prefixed with “0b” to indicate its binary nature. The method then proceeds to remove this prefix by slicing the string from the third character onward, discarding the “0b”. Finally, the method returns this modified string, representing the binary sum of the inputs a
and b
without the initial prefix, thus completing the binary addition process using Python’s builtin functions and string slicing technique.
The time complexity of the code is O(N), where N is the length of the longer input string, due to binarytointeger conversions and the reverse. The space complexity is similarly O(N), because of the storage requirements for the conversion results and the output binary string.

LeetCode3 weeks ago
LeetCode 2: Add Two Numbers Solution in Python

LeetCode3 weeks ago
LeetCode 1: Two Sum Solution in Python

LeetCode2 weeks ago
LeetCode 3: Longest Substring Without Repeating Characters Solution in Python

LeetCode2 weeks ago
LeetCode 7: Reverse Integer Solution in Python

LeetCode2 weeks ago
LeetCode 2942: Find Words Containing Character Solution in Python

LeetCode2 weeks ago
LeetCode 1480: Running Sum of 1D Array Solution in Python

LeetCode2 weeks ago
LeetCode 1512: Number of Good Pairs Solution in Python

LeetCode1 week ago
LeetCode 24: Swap Nodes in Pairs Solution in Python