Backspace String Compare
Easy
Topics
Given two strings s and t, return true if they are equal after typing them into empty text editors. # is a backspace character.
Example 1
# is a backspace. Both strings reduce to ac and ac, so the answer is true.Input: s = "ab#c", t = "ad#c" Output: true
Example 2
Input: s = "a##c", t = "#a#c" Output: true
Example 3
Input: s = "a#c", t = "b" Output: false
Constraints
- 1 <= s.length, t.length <= 200
- s and t contain lowercase letters and #.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A # deletes the character before it, and the question is whether two strings are equal once every deletion is applied.
The direct reading gives the solution: walk left to right, pushing letters and popping on #, and whatever remains is the typed text. A stack is the right structure because deletion always targets the most recent surviving character, which is exactly the top.
Two details make it correct rather than nearly correct. A # on an empty stack is a no-op, not an error — backspacing into an empty box does nothing. And the deletions interact: "a##c" deletes the a and then has nothing left to delete, so it reduces to "c", which equals what "#a#c" reduces to.
Worth knowing there is an O(1)-space alternative, because it is the standard follow-up. Walk both strings from the right, maintaining a skip count: on a # increment skip, on a letter either consume a skip or yield the character for comparison. Right to left works where left to right would not, because a character's fate depends only on the # symbols that come after it.
Approach
build(x): push letters, pop on#when the stack is non-empty, join at the end.- Compare the two built strings.
Dry Run
s = "ab#c" t = "ad#c"
'a' push [a] 'a' push [a]
'b' push [a,b] 'd' push [a,d]
'#' pop [a] '#' pop [a]
'c' push [a,c] 'c' push [a,c]
-> "ac" -> "ac" equal -> true
s = "a##c" t = "#a#c"
'a' push [a] '#' empty, no-op []
'#' pop [] 'a' push [a]
'#' empty, no-op [] '#' pop []
'c' push [c] 'c' push [c]
-> "c" -> "c" equal -> trueThe second pair is the one that breaks naive attempts: both strings contain a # with nothing to delete, and treating that as an error — or as deleting something — gives the wrong answer.
Complexity
- Time — O(n + m): each character of each string is pushed and popped at most once.
- Space — O(n + m): the two built strings. The two-pointer variant described above is O(1), comparing in place without materialising either result — that is the answer to expect as a follow-up, and the reason to mention it even though the stack version is what is shown.
Common Pitfalls
- Popping without checking the stack is non-empty. A leading
#is legal input and must be ignored, not an error. - Comparing lengths early to exit. Two strings of different raw lengths can reduce to the same text, which is the whole problem.
- Deleting in place with string concatenation per
#, which is O(n^2). - Trying the skip-count trick left to right. A character's survival depends on the
#symbols after it, so the scan has to run right to left. - Treating
#as a literal character to compare. It is an instruction, never part of the result.
Full Solution — all languages
class Solution:
def backspaceCompare(self, s, t):
def build(x):
stack = []
for c in x:
if c == "#":
if stack: stack.pop()
else:
stack.append(c)
return "".join(stack)
return build(s) == build(t)import java.util.*;
class Solution {
public boolean backspaceCompare(String s, String t) {
return build(s).equals(build(t));
}
String build(String x) {
StringBuilder sb = new StringBuilder();
for (char c : x.toCharArray()) {
if (c == '#') {
if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
} else sb.append(c);
}
return sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool backspaceCompare(string s, string t) {
auto build = [](string x) {
string stack;
for (char c : x) {
if (c == '#') {
if (!stack.empty()) stack.pop_back();
} else stack.push_back(c);
}
return stack;
};
return build(s) == build(t);
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var backspaceCompare = function(s, t) {
const build = (x) => {
const stack = [];
for (const c of x) {
if (c === '#') {
if (stack.length) stack.pop();
} else stack.push(c);
}
return stack.join('');
};
return build(s) === build(t);
};