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)
Difficulty
and has an acceptance rate of about 50% (2+ million submissions).
Typical patterns to solve this problem:
- Simulation
- Stack
- String
- Two Pointers
AI Disclaimer
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.
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
sortis an empty string, the loop infinalexecutes zero iterations, leavingstackempty 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 innerif 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 emptystack. 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
appendandpopoperations 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
joincall 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:
- The
backspaceComparemethod receives two strings,sandt. - It defines the nested
finalfunction, which:- Initializes an empty list
stack. - Iterates over each character of the supplied text.
- Applies backspace logic using conditional
poporappend. - Joins the list into a final string and returns it.
- Initializes an empty list
finalis called withs, producing the resolved version ofs.finalis called witht, producing the resolved version oft.- The two resulting strings are compared for equality, and the Boolean result is returned to the caller.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 1598: Crawler Log Folder
- problem 2390: Removing Stars From a String
Solved On The Same Day
- problem 812: Largest Triangle Area
- problem 824: Goat Latin
- problem 791: Custom Sort String
- problem 794: Valid Tic-Tac-Toe State
- problem 807: Max Increase to Keep City Skyline
- problem 813: Largest Sum of Averages
- problem 814: Binary Tree Pruning
- problem 825: Friends Of Appropriate Ages
- problem 848: Shifting Letters
- problem 849: Maximize Distance to Closest Person
- problem 815: Bus Routes
Extra
- 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