# Add Binary

## Problem

Given two binary strings `a` and `b`, return *their sum as a binary string*.

{% hint style="info" %}
For example:

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

```
Input: a = "1010", b = "1011"
Output: "10101"
```

{% endhint %}

### Thought Process

![](/files/-MNARea6e3evkGp-FNmE)

* Notice how when we add two digits, there can potentially be a digit that carries over (i.e., adding 1 + 1 = 0 but this translates to a carried 1)

* We will have two pointers pointing at the end of both strings to simulate adding them together

* Since we are appending to a string for our final output, we have to reverse this string at the end to get the corret number (since appending to the string adds to the element to the back)&#x20;

## Solution

```
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        res = ""
        i = len(a) - 1
        j = len(b) - 1
        carry = 0
        while(i>= 0 or j >= 0):
            numSum = carry
            if i >= 0:
                numSum+=int(a[i]) #you can do either one to get the integer representation
            if j >= 0:
                numSum+=ord(b[j]) - ord('0')
            i-=1
            j-=1
            if numSum > 1:
                carry = 1
            else:
                carry = 0 
            res+=str(numSum%2) #mod by 2 in case we have 1+1+1
        
        if carry != 0: #if we have a carry left over
            res+=str(carry)
        return res[::-1]
```

## Key Facts

* Two pointers to traverse through both integer strings

* After adding the two numbers, we need to check if the sum is greater than 1, if so then carry = 1

* After the additon, we need to mod by 2 and append this to our result.
  * Mod by 2 because we can potentially have 1+1+1 which results in 3 but would translate to a 1.

## Time Complexity

* **Time**: $$O(n)$$&#x20;
* **Space:** $$O(1)$$&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/strings/string-math/add-binary.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
