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 INPUT String s = "ab#c" a b # c String t = "ad#c" a d # c # = Backspace Compare after processing all backspaces ALGORITHM STEPS 1 Two Pointers Start from end of both strings 2 Count Backspaces Track # count, skip chars 3 Compare Characters Compare valid chars only 4 Process Result Return true if all match Processing: s: ab#c --> "ac" t: ad#c --> "ac" "ac" == "ac" [OK] FINAL RESULT After Processing: String s becomes: a c String t becomes: a c Output: true Both strings are equal after backspaces [OK] Key Insight: Use two pointers starting from the end of both strings. When encountering '#', increment a skip counter. When the counter is positive and we see a regular char, decrement counter and skip that char. This achieves O(n) time and O(1) space complexity - optimal solution without building new strings! TutorialsPoint - Backspace String Compare | Optimal Two-Pointer Solution
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