Connect with us

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 built-in functions to achieve binary addition in a single line of code.

Published

on

In this tutorial article, I go through my Python solution to the Add Binary problem from LeetCode. My code uses Python’s built-in functions for binary-decimal 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 built-in functions and string slicing technique.

Screenshot of my successful tests for my Python solution to LeetCode's Add Binary problem, which beat 86% of other Python 3 submissions in runtime.
My successful tests for my Python solution to LeetCode’s Add Binary problem, which beat 86% of other Python 3 submissions in runtime.

The time complexity of the code is O(N), where N is the length of the longer input string, due to binary-to-integer 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.

Trending