How to Solve 'Add Binary' on LeetCode: A Step-by-Step Guide

How to Solve 'Add Binary' on LeetCode: A Step-by-Step Guide

Intuition

The problem involves adding two binary numbers represented as strings. My first thought was to convert the binary strings into integers, perform the addition, and then convert the result back into a binary string. Python's built-in functions make this process straightforward.


Approach

  1. Convert Binary Strings to Integers:

    • Use int(a, 2) and int(b, 2) to convert the binary strings a and b into integers.
  2. Add the Integers:

    • Perform the addition directly using +.
  3. Convert the Sum Back to Binary:

    • Use format(sum, 'b') to convert the result into a binary string without the 0b prefix.

This approach leverages Python's built-in functions for efficient conversion and formatting, eliminating the need for manual binary arithmetic.


Complexity

  • Time complexity:
    $$O(n + m)$$
    Where (n) and (m) are the lengths of the binary strings a and b. The conversions (int and format) operate in linear time with respect to the string lengths.

  • Space complexity:
    $$O(n + m)$$
    Additional space is used for storing the converted integers and the resulting binary string.


Code

class Solution(object):
    def addBinary(self, a, b):
        return format(int(a, 2) + int(b, 2), 'b')

Example Test Cases

  1. Input: a = "11", b = "1"
    Output: "100"
    Explanation: The binary addition of 11 and 1 results in 100.

  2. Input: a = "1010", b = "1011"
    Output: "10101"
    Explanation: The binary addition of 1010 and 1011 results in 10101.

  3. Input: a = "0", b = "0"
    Output: "0"
    Explanation: The binary addition of 0 and 0 results in 0.


Connect with Me

If you found this solution helpful, feel free to connect with me on LinkedIn! Let’s grow and share knowledge together. 😊


Did you find this article valuable?

Support VISHWANATH'S BLOG by becoming a sponsor. Any amount is appreciated!