# Backspace String Compare

## Problem

Given two strings `S` and `T`, return if they are equal when both are typed into empty text editors. `#` means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

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

```
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
```

```
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
```

```
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
```

```
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes 
"b"
```

{% endhint %}

## Solution

```
class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        i = len(S)-1
        j = len(T)-1
        backSpaceS = 0
        backSpaceT = 0
        
        while i >= 0 or j >= 0:
            while i >= 0:
                if S[i] == '#':
                    backSpaceS+=1
                    i-=1
                elif S[i] != '#' and backSpaceS > 0:
                    i-=1 #'deleting' the next character by skipping it
                    backSpaceS-=1
                else:
                    break
            
            while j >= 0:
                if T[j] == '#':
                    backSpaceT+=1
                    j-=1
                elif T[j] != '#' and backSpaceT > 0:
                    j-=1
                    backSpaceT-=1
                else:
                    break
                    
            if S[i] != T[j]:
                return False
            #this checks if all the elements of one string is deleted but not the 
            #other
            if (i < 0 and j >= 0) or (j < 0 and i >= 0):
                return False
               
            i-=1
            j-=1
        print(i,j)
        return True
                    
#inner while loop main purpose is to check for
#backspaces and control the deletion          
  
#Time: O(N+M)
#Space: O(1)              
```


---

# 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/two-pointers/backspace-string-compare.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.
