Practice › Stack & Queue
Backspace String Compare
Easy · Stack & Queue · Asked at Google, Amazon, Meta, TCS, Infosys
Both strings are typed into an editor where # means backspace (deleting the previous character, if any). Print YES if the two final texts are equal, otherwise NO.
Input
Two lines: s and t (lowercase letters and #).
Output
YES or NO.
Constraints
- 1 ≤ |s|, |t| ≤ 10^5
Simulate each string with a stack (push letters, pop on #) and compare. For O(1) memory, walk both strings from the end, skipping characters that a later # deletes.
Example 1
Input
ab#c ad#c
Output
YES
Example 2
Input
a#c b
Output
NO
Hints
- Typing with backspace is a stack: letters push, # pops.
- Build both final texts and compare them.
- For O(1) memory, scan from the end and count pending backspaces.
Approach
Simulate each string with a stack (a std::string or StringBuilder works as one): push each letter, pop on # if not empty. Compare the two results. The two-pointer O(1)-space version walks both strings backwards, skipping characters cancelled by #, and compares the surviving characters one by one.
Complexity: O(|s| + |t|) time · O(|s| + |t|) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
string typed(const string &s) {
string st;
for (char c : s) {
if (c == '#') {
if (!st.empty()) st.pop_back();
} else st.push_back(c);
}
return st;
}
int main() {
string s, t;
cin >> s >> t;
cout << (typed(s) == typed(t) ? "YES" : "NO") << "\n";
return 0;
}Python solution
import sys
def typed(s):
st = []
for c in s:
if c == "#":
if st:
st.pop()
else:
st.append(c)
return st
s, t = sys.stdin.read().split()[:2]
print("YES" if typed(s) == typed(t) else "NO")Java solution
import java.io.*;
public class Main {
static String typed(String s) {
StringBuilder st = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == '#') {
if (st.length() > 0) st.deleteCharAt(st.length() - 1);
} else st.append(c);
}
return st.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine().trim(), t = br.readLine().trim();
System.out.println(typed(s).equals(typed(t)) ? "YES" : "NO");
}
}Solve Backspace String Compare online · All practice problems