Problem 844

Abstract / Summary

Compare two strings after applying backspace rules to remove characters before comparing them.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0844.py

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        def final(text):
            stack = []
            for c in text:
                if c == "#":
                    if stack:
                        stack.pop()
                else:
                    stack.append(c)
            return "".join(stack)

        return final(s) == final(t)
13 lines | 384 bytes | submitted October 9, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (2+ million submissions).

Typical patterns to solve this problem:
  • Simulation
  • Stack
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method backspaceCompare. This method determines whether two input strings, s and t, are equivalent after interpreting the character # as a backspace operation. The core logic is encapsulated in a nested helper function named final, which processes each string independently and returns the resulting text after applying all backspace actions. The final comparison is performed by checking the equality of the two processed strings.

Core Processing Function

The helper final function builds the effective string by iterating over each character of the input text. A Python list named stack serves as a mutable container that mimics stack behavior. For every character c encountered:

if c == "#":
    if stack:
        stack.pop()
else:
    stack.append(c)

When c is a backspace symbol (#), the function removes the most recently added character from stack if the stack is not empty. This conditional guard ensures that attempts to backspace beyond the start of the string are safely ignored, effectively handling cases where the input begins with one or more # characters. If c is any other character, it is appended to stack. After processing the entire input, the list is joined into a single string:

return "".join(stack)

The use of join on a list of characters is an efficient way to construct the final string without repeated concatenation.

Comparison Logic

The public method backspaceCompare invokes final on both input strings and directly returns the result of the equality test:

return final(s) == final(t)

Because the helper returns the fully resolved strings, the equality operator performs a straightforward character-by-character comparison, yielding a Boolean outcome.

Edge Cases Handled

The algorithm gracefully manages several edge conditions:

  • Empty Input - When either s or t is an empty string, the loop in final executes zero iterations, leaving stack empty and returning an empty string. The comparison correctly reflects equality when both are empty or inequality when only one is empty.

  • Leading Backspaces - If a string starts with one or more # characters, the inner if stack: guard prevents attempts to pop from an empty list. Consequently, leading backspaces have no effect, matching the expected behavior of a backspace that cannot delete beyond the beginning of the text.

  • Consecutive Backspaces - Multiple # symbols in a row trigger successive pop operations, each guarded by the same emptiness check. This correctly removes the appropriate number of preceding characters, or does nothing if there are insufficient characters to delete.

  • All Characters Deleted - A string composed entirely of characters followed by enough # symbols to erase them results in an empty stack. The final string returned is empty, and the comparison accounts for this scenario.

  • Mixed Alphanumeric and Symbol Characters - The function treats any character other than # as a literal to be retained, ensuring that letters, digits, punctuation, and whitespace are processed uniformly.

Performance Optimizations

The implementation exhibits several performance-focused choices:

  • In-Place Stack Using List - Python lists provide O(1) amortized time for append and pop operations at the end of the list. By using a list as a stack, the algorithm avoids the overhead of more complex data structures while maintaining constant-time updates for each character.

  • Single Pass Processing - Each input string is traversed exactly once. The loop processes characters sequentially, applying backspace logic on the fly, which eliminates the need for multiple passes or auxiliary scans.

  • Deferred String Construction - Characters are accumulated in a list rather than concatenated into a string during iteration. Since string concatenation in Python creates a new object each time, deferring the final assembly to a single join call reduces memory allocations and improves runtime efficiency.

  • Early Equality Check - By returning the result of final(s) == final(t) directly, the method leverages Python’s short-circuit evaluation. If the two processed strings differ early, the comparison can terminate without examining the remainder of the longer string, saving unnecessary work in the equality operation.

Code Flow Summary

The execution proceeds as follows:

  1. The backspaceCompare method receives two strings, s and t.
  2. It defines the nested final function, which:
    • Initializes an empty list stack.
    • Iterates over each character of the supplied text.
    • Applies backspace logic using conditional pop or append.
    • Joins the list into a final string and returns it.
  3. final is called with s, producing the resolved version of s.
  4. final is called with t, producing the resolved version of t.
  5. The two resulting strings are compared for equality, and the Boolean result is returned to the caller.
written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two special boxes full of alphabet blocks. Sometimes, you make a mistake while putting blocks into the box, and you use a magic eraser block that looks like a little hashtag symbol.

Whenever that eraser block appears, it automatically grabs the very last block you put in the box and whisks it away, disappearing along with it. If you try to use an eraser but the box is already empty, nothing happens because there is nothing to take out.

To solve this puzzle, you go through each box one by one. You pick up the blocks in order and put them into a new, organized pile. When you see a regular letter, you add it to the top of the pile. When you see the magic eraser block, you take the top letter off the pile.

After you finish looking at every single block in the first box, you will be left with a final string of letters. You repeat this whole process with the second box to get its own final string of letters. Once both piles are finished, you just hold them up side by side to see if they look exactly the same. If the piles match perfectly, the puzzle is solved.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.31 | σ = 0.82

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
43 links | 28 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 easy 8 medium 1 hard
12 solutions   October 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality