Backspace String Compare - 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.

Note: After backspacing an empty text, the text will continue to remain empty.

Follow up: Can you solve it in O(1) space?

Input & Output

Example 1 — Basic Backspace
$ Input: s = "ab#c", t = "ad#c"
Output: true
💡 Note: Both strings become "ac" after processing backspaces: s removes 'b', t removes 'd'
Example 2 — Multiple Backspaces
$ Input: s = "ab##", t = "c#d#"
Output: true
💡 Note: Both strings become empty after processing: s removes 'b' then 'a', t removes 'd' then 'c'
Example 3 — Different Results
$ Input: s = "a#c", t = "b"
Output: false
💡 Note: s becomes "c" after removing 'a', t remains "b", so they are not equal

Constraints

  • 1 ≤ s.length, t.length ≤ 200
  • s and t only contain lowercase letters and '#' characters

Visualization

Tap to expand
Backspace String Compare: Text Editor SimulationCompare "ab#c" and "ad#c" after applying backspacesString s: "ab#c"Type 'a' → aType 'b' → abBackspace → aType 'c' → acString t: "ad#c"Type 'a' → aType 'd' → adBackspace → aType 'c' → acFinal: "ac"from sFinal: "ac"from t"ac" = "ac"Result: true
Understanding the Visualization
1
Input
Two strings with # representing backspaces
2
Process
Apply backspaces to build final strings
3
Compare
Check if final strings are equal
Key Takeaway
🎯 Key Insight: Process strings from right to left to handle backspaces efficiently without building intermediate strings
Asked in
Google 25 Facebook 20 Amazon 15
125.0K Views
Medium Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen