Backspace String Compare
You are given two strings where the character # represents a backspace key. When you see #, it removes the character immediately before it. If there is no character before the #, nothing happens. After applying all backspaces to both strings, determine if the resulting strings are equal.
A stack handles this naturally: iterate through each character, push non-backspace characters onto the stack, and pop the top when you encounter # (if the stack is not empty). At the end, compare the two stacks.
For example, "ab#c" becomes "ac". "ad#c" also becomes "ac", so they match. But "a##c" becomes "c" because both backspaces remove the a.
Example Input & Output
Becomes "c" vs "b".
Both become "ac".
Both become empty string.
Algorithm Flow

Solution Approach
Define a helper function that takes a string and returns the processed result. Iterate through each character. If it's not #, push it. If it's # and the stack is not empty, pop. Then compare the two resulting strings.
Time complexity is O(n). Space complexity is O(n) for the stacks.
Best Answers
import java.util.*;
class Solution {
public boolean solution(String s, String t) {
return build(s).equals(build(t));
}
String build(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '#') { if (!stack.isEmpty()) stack.pop(); }
else stack.push(c);
}
StringBuilder sb = new StringBuilder();
for (char c : stack) sb.append(c);
return sb.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
