Backspace String Compare
Decide whether two strings type the same text when # is the backspace key.
You are given two strings st#truefalse
Example 1
Output: true
Explanation: both become "ac".
Example 2
Output: true
Explanation: both become "".
Example 3
Output: false
Explanation: s becomes "c" and t stays "b".
The Idea
When you type a message and press backspace, the last character you typed disappears. Each string here is a record of keys pressed: a letter is typed, and #"ab#c"#"ad#c"true
The direct way is to do exactly that: type both strings out and compare the two results. That works, but it builds two new pieces of text as long as the inputs. Can we compare the strings without building anything?
Reading from left to right makes that hard, because a letter's fate is decided later. When you reach b in "ab#c"#"ab#c"#
Look at the picture below. Each box is one character, and its position in the string, counting from 0, is called its index.
In both strings, the #st
So the typed text never has to exist. One marker per string walks from the right end to the left, stops on the next letter that survives, and the two letters are compared. Keeping one marker in each input and moving them step by step is a form of the two-pointer technique, which
Solution Approach
Turning that idea into code means settling three things: whether to build the typed text at all, how to find the next letter that survives, and how to compare the two strings until they run out.
Building the typed text
Why not simply type the strings out? A StringBuilder#
Finding the next surviving letter
How does a marker know whether a letter survives? It counts the backspaces that are still waiting to delete something, in a counter called skip
- on a
, add one to# ;skip - on a letter while
is above 0, that letter is deleted, so subtract one fromskip ;skip - on a letter while
is 0, that letter survives, and the walk stops there.skip
If the walk goes past index 0, the string has no surviving letter left. A #skip
Comparing the two strings
What decides the answer? Each round finds the next surviving letter in st
Java Solution
The method backspaceCompare
- First, put the marker
on the last index ofi and the markers on the last index ofj .t - Loop while at least one marker is still inside its string. Each round, move both markers to their next surviving letter with the helper
. It walks left with its ownnextKept counter, following the three rules forskip listed earlier, and returns -1 when no surviving letter is left.skip - If
ori is now -1, return whether both are:j .i < 0 && j < 0 - Otherwise compare
withs.charAt(i) . If they differ, returnt.charAt(j) . If they match, movefalse andi one place left and start the next round.j - If the loop ends because both markers have left their strings, every pair matched, so return
.true
The main"xy##z""z""#a""a""a""ba"
public class BackspaceStringCompare {
public static boolean backspaceCompare(String s, String t) {
int i = s.length() - 1;
int j = t.length() - 1;
while (i >= 0 || j >= 0) {
i = nextKept(s, i); // index of the next character that survives
j = nextKept(t, j);
if (i < 0 || j < 0) {
return i < 0 && j < 0; // equal only if both strings are used up
}
if (s.charAt(i) != t.charAt(j)) {
return false;
}
i--;
j--;
}
return true;
}
// Walk left from index i and return the first character no '#' deletes, or -1
private static int nextKept(String str, int i) {
int skip = 0; // backspaces waiting to delete something
while (i >= 0) {
if (str.charAt(i) == '#') {
skip++;
} else if (skip > 0) {
skip--; // this character is deleted
} else {
return i;
}
i--;
}
return -1;
}
public static void main(String[] args) {
System.out.println(backspaceCompare("ab#c", "ad#c")); // "ac" and "ac"
System.out.println(backspaceCompare("ab##", "c#d#")); // "" and ""
System.out.println(backspaceCompare("a#c", "b")); // "c" and "b"
System.out.println(backspaceCompare("xy##z", "z")); // "z" and "z"
System.out.println(backspaceCompare("#a", "a")); // "a" and "a"
System.out.println(backspaceCompare("a", "ba")); // "a" and "ba"
}
}
Running it prints:
true
true
false
true
true
false
The three examples give truetruefalse"xy##z"#true
The fifth line is true"#a"#"a"
Look at the last line: "a""ba"falsesti >= 0 || j >= 0&&struetrue
Complexity
Each marker only ever moves left, so the work is one pass over each string.
- Time: O(m + n), where m and n are the lengths of
ands . Across all calls tot and all rounds,nextKept andi visit each character at most once.j - Space: O(1). The method keeps two indexes and a
counter, and never builds the typed text.skip
The StringBuilder