Backspace String Compare - Problem

Imagine you're typing on two different text editors with a special backspace key represented by the '#' character. Your task is to determine if both editors will display the same final text after processing all the keystrokes.

The Challenge: Given two strings s and t, return true if they are equal when both are typed into empty text editors. The '#' character means backspace - it removes the previous character (if any exists). If you backspace on an empty text editor, it remains empty.

Example: "ab#c" becomes "ac" (type 'a', type 'b', backspace removes 'b', type 'c')

Input & Output

example_1.py โ€” Basic backspace operations
$ Input: s = "ab#c", t = "ad#c"
โ€บ Output: true
๐Ÿ’ก Note: Both strings become "ac" after processing backspaces: s: type 'a', type 'b', backspace (remove 'b'), type 'c' โ†’ "ac". t: type 'a', type 'd', backspace (remove 'd'), type 'c' โ†’ "ac".
example_2.py โ€” Multiple backspaces
$ Input: s = "ab##", t = "c#d#"
โ€บ Output: true
๐Ÿ’ก Note: Both strings become empty after processing: s: type 'a', type 'b', backspace twice (remove 'b', then 'a') โ†’ "". t: type 'c', backspace (remove 'c'), type 'd', backspace (remove 'd') โ†’ "".
example_3.py โ€” Backspace on empty string
$ Input: s = "a#c", t = "b"
โ€บ Output: false
๐Ÿ’ก Note: s becomes "c" (type 'a', backspace, type 'c'), while t remains "b". Since "c" โ‰  "b", the result is false.

Visualization

Tap to expand
Text Editor 1Input: "ab#c"Process: a โ†’ ab โ†’ a โ†’ acOutput: "ac"Text Editor 2Input: "ad#c"Process: a โ†’ ad โ†’ a โ†’ acOutput: "ac"COMPAREEQUALTRUE
Understanding the Visualization
1
Start Typing
Both users begin typing their respective strings character by character
2
Handle Backspaces
When '#' is encountered, the previous character is deleted from the display
3
Compare Results
After processing all keystrokes, compare the final text on both screens
Key Takeaway
๐ŸŽฏ Key Insight: Working backwards eliminates the need to build complete strings - we can directly compare the final valid characters while efficiently handling backspaces.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n + m)

Single pass through both strings where n and m are string lengths

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a few variables for pointers and backspace counting

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length, t.length โ‰ค 200
  • s and t only contain lowercase letters and '#' characters
  • Follow up: Can you solve it in O(n) time and O(1) space?
Asked in
Google 28 Facebook 15 Apple 12 Microsoft 8
89.6K Views
Medium Frequency
~15 min Avg. Time
2.8K 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