Backspace String Compare

Decide whether two strings type the same text when # is the backspace key.

You are given two strings s and t. Imagine typing each one into an empty text editor, where the character # is the backspace key: it deletes the character typed before it. A backspace on empty text does nothing. Return true if both strings leave the same text on the screen, and false otherwise.

Example 1
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: both become "ac".
Example 2
Input: s = "ab##", t = "c#d#"
Output: true
Explanation: both become "".
Example 3
Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" and t stays "b".
Solution

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 # presses backspace. Typing "ab#c" puts a, then b, then the # removes b, and c comes last, so the screen shows "ac". Typing "ad#c" also ends with "ac", which is why Example 1 is 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", you cannot tell yet whether it stays; only the # after it says so. Read from the right end instead, and the backspaces come first. Backwards, "ab#c" reads c, then #, then b. By the time you reach b, you already know one backspace is waiting, so b is gone.

Look at the picture below. Each box is one character, and its position in the string, counting from 0, is called its index.

s = ab#c and t = ad#c, read from the right. In each string the # at index 2 deletes the letter at index 1. The letters that survive, c at index 3 and a at index 0, are compared in pairs: c with c first, then a with a.

In both strings, the # at index 2 deletes the letter at index 1: b in s and d in t. The letters that survive are c at index 3 and a at index 0. Read from the right, they pair up: c with c first, then a with a. Every pair matches, and both strings run out of letters at the same time, so the typed texts are equal.

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 Two Pointers Basics introduces.

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, a Java class that holds text you can change, can append each letter and delete its last character on every #. Comparing the two results then gives the answer. It is fast, but it needs extra memory as large as both strings. Reading from the right needs only two markers and a counter.

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, and walks left from where it stands:

  • on a #, add one to skip;
  • on a letter while skip is above 0, that letter is deleted, so subtract one from skip;
  • on a letter while skip is 0, that letter survives, and the walk stops there.

If the walk goes past index 0, the string has no surviving letter left. A # with nothing to its left raises skip but finds no letter to delete, which matches a backspace on empty text doing nothing.

Comparing the two strings

What decides the answer? Each round finds the next surviving letter in s and in t. If the two letters differ, the texts differ. If one string has a surviving letter left and the other has none, one text is longer, so they differ too. If both run out in the same round, every pair matched and the texts are equal. After a match, both markers step one place left, past the letters just compared.

Java Solution

The method backspaceCompare works in these steps:

  1. First, put the marker i on the last index of s and the marker j on the last index of t.
  2. Loop while at least one marker is still inside its string. Each round, move both markers to their next surviving letter with the helper nextKept. It walks left with its own skip counter, following the three rules for skip listed earlier, and returns -1 when no surviving letter is left.
  3. If i or j is now -1, return whether both are: i < 0 && j < 0.
  4. Otherwise compare s.charAt(i) with t.charAt(j). If they differ, return false. If they match, move i and j one place left and start the next round.
  5. If the loop ends because both markers have left their strings, every pair matched, so return true.

The main method runs the three examples and three more cases. "xy##z" against "z" has two backspaces in a row, "#a" against "a" has a backspace on empty text, and in "a" against "ba", one string is the end of the other.

Java
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:

Output
true
true
false
true
true
false

The three examples give true, true and false, as expected. On the fourth line, "xy##z" read from the right keeps z, and then its two # characters delete y and x, so only "z" is left and the answer is true.

The fifth line is true as well. After a matches a, the walk in "#a" meets a # with nothing to its left, goes past index 0 and returns -1. The walk in "a" also returns -1, so both strings ran out together.

Look at the last line: "a" and "ba" give false. After a matches a, s has no letters left but t still has b. That is why the loop condition is i >= 0 || j >= 0. With && instead, the loop would stop as soon as s ran out and return true, never looking at the b. We ran that version on this input, and it printed true.

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 s and t. Across all calls to nextKept and all rounds, i and j visit each character at most once.
  • Space: O(1). The method keeps two indexes and a skip counter, and never builds the typed text.

The StringBuilder way works like a stack, a list where items are added and removed only at the end. For a problem where a stack is the right tool, see Remove All Adjacent Duplicates in String II.