Solving Leetcode Interviews in Seconds with AI: Add Binary
Introduction
In this blog post, we will explore how to solve the LeetCode problem "67" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: 1 <= a.length, b.length <= 104 a and b consist only of '0' or '1' characters. Each string does not contain leading zeros except for the zero itself.
Explanation
Here's a breakdown of the solution and the Python code:
High-Level Approach:
- Iterate through the binary strings from right to left, similar to how we perform manual addition.
- Maintain a
carryvariable to handle overflow when the sum of bits at a particular position exceeds 1. - Append the resulting bit (0 or 1) to the beginning of the
resultstring.
Complexity:
- Runtime Complexity: O(max(len(a), len(b)))
- Storage Complexity: O(max(len(a), len(b))) - due to the
resultstring
Code
def addBinary(a: str, b: str) -> str:
"""
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
"""
result = ""
i = len(a) - 1
j = len(b) - 1
carry = 0
while i >= 0 or j >= 0 or carry:
sum_bits = carry
if i >= 0:
sum_bits += int(a[i])
i -= 1
if j >= 0:
sum_bits += int(b[j])
j -= 1
result = str(sum_bits % 2) + result
carry = sum_bits // 2
return result