Backspace String Compare — LeetCode 844 Python Solution

EasyStackTwo PointersStringSimulation
Problem
#844
Pattern
Stack
Reading time
5 min

The problem

Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

Example

Input
s = "ab#c", t = "ad#c"
Output
true
Explanation
Both s and t become "ac".

Python solution

Python
class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        i, j, skip1, skip2 = len(s) - 1, len(t) - 1, 0, 0
        while i >= 0 or j >= 0:
            while i >= 0:
                if s[i] == '#':
                    skip1 += 1
                    i -= 1
                elif skip1:
                    skip1 -= 1
                    i -= 1
                else:
                    break
            while j >= 0:
                if t[j] == '#':
                    skip2 += 1
                    j -= 1
                elif skip2:
                    skip2 -= 1
                    j -= 1
                else:
                    break
            if i >= 0 and j >= 0:
                if s[i] != t[j]:
                    return False
            elif i >= 0 or j >= 0:
                return False
            i, j = i - 1, j - 1
        return True

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 844. Backspace String Compare is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 844. Backspace String Compare?
LeetCode 844. Backspace String Compare is rated Easy on LeetCode.
What is the time complexity of LeetCode 844. Backspace String Compare?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 844. Backspace String Compare?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 844. Backspace String Compare cover?
LeetCode 844. Backspace String Compare is tagged Stack, Two Pointers, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview