Backspace String Compare
1 approach, code in every language
Problem description
You are given two strings s and t, where the character '#' represents a backspace key. Typing a normal character appends it, while typing '#' deletes the character immediately before it (if there is one).
Return true if the two strings produce the same text after all backspaces have been applied, and false otherwise. Note that a backspace on an already-empty text simply does nothing.
A natural solution builds each final string on a stack, but the problem can also be solved in O(1) extra space by scanning both strings from the back and skipping over characters that get deleted.
Example 1
Input: s = "ab#c", t = "ad#c"
Output: true
Both become "ac": in s the b is deleted, and in t the d is deleted.
Example 2
Input: s = "a#c", t = "b"
Output: false
s becomes "c" while t stays "b", so they differ.
Constraints
1 <= s.length, t.length <= 200s and t contain only lowercase English letters and the '#' character
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Strike Marks On Two Tapes is our own problem on the technique behind Backspace String Compare: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free