Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #67: Add Binary

In this guide, we solve Leetcode #67 Add Binary in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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.

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: Bit Manipulation, Math, String, Simulation

Intuition

The problem structure lets us track state with bitwise operations.

Bit operations are constant time and avoid extra memory.

Approach

Apply XOR/AND/OR and shifts to maintain the required invariant.

Aggregate the result in a single pass.

Steps:

  • Identify a bitwise invariant.
  • Combine values with bit operations.
  • Return the aggregated result.

Example

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

Python Solution

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

The time complexity is O(max⁡(m,n))O(\max(m, n))O(max(m,n)), where mmm and nnn are the lengths of strings aaa and bbb respectively. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy