Removing Stars From a String

Delete every star in a string together with the closest letter on its left, in one pass.

Given a string s made of lowercase letters and stars (*), remove every star. Each star takes one letter with it: the closest letter to its left that has not been removed yet. Return what is left. Every star is guaranteed to have such a letter, and the result is the same whatever order the stars are handled in.

Example 1
Input: s = "cs**cod*e"
Output: "coe"
Explanation: the first star removes 's', the second removes the first 'c', and the third removes 'd'.
Example 2
Input: s = "erase*****"
Output: ""
Explanation: five stars remove all five letters.
Solution

The Idea

A star behaves like the backspace key. When you type cs and press backspace twice, the s disappears first and then the c. Typing cod, one more backspace and an e leaves coe on the screen, which is the answer to Example 1.

Each press of backspace removes the letter typed most recently among those still on the screen. A star does the same, because the closest letter on its left that is still there is the newest one kept so far. Look at the picture below, which reads cs**cod*e one character at a time.

Reading cs**cod*e one character at a time. Each letter goes on top of the kept letters; each star removes the letter on top: first s, then c, then d. The kept letters at the end are c, o, e.

The top row is the character read, and below it are the kept letters after it, with the newest one on top. The letters c and s pile up. The first star removes s, the one on top, and the second star removes c, which leaves the pile empty. Then c, o and d pile up, the third star removes d, and e goes on top. Read from the bottom, the last column says coe.

So a star never needs to search. The letter it removes is always the one on top of the pile. A pile where you only add and remove at the top is called a stack, and the last item added is the first one taken out.

Solution Approach

Turning the pile into code comes down to three points: why a stack beats editing the string star by star, which Java type to use as the stack, and how to read the answer out of it in the right order.

Searching for each star's letter

What if we just edit the string, star by star? For each star, walk left to the closest letter, then delete both from the string. Walking left and deleting from the middle of a string can each take as many steps as the string is long. With n characters and up to n/2 stars, that adds up to about n² steps.

The stack avoids both costs. Reading left to right, each letter is added on top, and each star removes the top. Neither step depends on how long the string is.

A StringBuilder as the stack

Which Java type should hold the kept letters? A StringBuilder is a string that can be changed in place. Its append adds a character at the end, and deleteCharAt(length() - 1) removes the last one. If the end counts as the top, those two calls are exactly "add on top" and "remove the top", and neither has to move the other characters.

Reading the answer in the right order

How do the kept letters become the answer? In the StringBuilder they already sit in reading order, from the oldest at the start to the newest at the end, so toString() is the answer.

A Deque<Character>, Java's usual stack type, works for the removing too. But taking the letters out with pop() gives the newest one first, so the answer comes out backwards and has to be reversed. The check after the code shows this.

Java Solution

The method removeStars works in these steps:

  1. First, create an empty StringBuilder named kept. It is the stack of kept letters, with its end as the top.
  2. Loop over the characters of s from left to right, one character c at a time.
  3. When c is a star, remove the last character of kept with deleteCharAt(kept.length() - 1). The problem promises a letter is always there to remove.
  4. Otherwise c is a letter, so add it to the end of kept with append(c).
  5. After the loop, return kept.toString().

The main method runs both examples, a string with no stars, a string where two stars in a row empty the stack before the last letter, and a string where every letter is removed right after it is typed. Each result is printed in quotes, so an empty string shows as "".

Java
public class RemovingStarsFromString {

    public static String removeStars(String s) {
        StringBuilder kept = new StringBuilder();       // used as a stack of letters
        for (char c : s.toCharArray()) {
            if (c == '*') {
                kept.deleteCharAt(kept.length() - 1);  // drop the most recent kept letter
            } else {
                kept.append(c);                        // keep the letter, on top
            }
        }
        return kept.toString();
    }

    public static void main(String[] args) {
        System.out.println("\"" + removeStars("cs**cod*e") + "\"");
        System.out.println("\"" + removeStars("erase*****") + "\"");
        System.out.println("\"" + removeStars("stack") + "\"");
        System.out.println("\"" + removeStars("ab*c**d") + "\"");
        System.out.println("\"" + removeStars("x*y*z*") + "\"");
    }
}

Running it prints:

Output
"coe"
""
"stack"
"d"
""

"coe" and the empty "" on the first two lines match Examples 1 and 2. With no stars, "stack" comes back unchanged.

Look at the fourth line, "d", from ab*c**d. The first star removes b, leaving a. Then c goes on top, and the two stars remove c and then a. Only d, typed after them, stays. The last line is empty because in x*y*z* each star removes the letter typed just before it.

Here is the Deque version from the Solution Approach, run on Example 1: the same loop with push and pop, then popping every letter into a StringBuilder.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class DequeOrderCheck {
    public static void main(String[] args) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : "cs**cod*e".toCharArray()) {
            if (c == '*') {
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        System.out.println("popped in order: \"" + sb + "\"");
        System.out.println("reversed:        \"" + sb.reverse() + "\"");
    }
}

Running it prints:

Output
popped in order: "eoc"
reversed:        "coe"

The first line, "eoc", is the right letters in the wrong order, because e was added last and comes out first. Only after reverse() does it read "coe".

The original implementation, RemovingStarsFromString.java, is on GitHub.

Complexity

The work is one pass over the string, with one small step per character.

  • Time: O(n), because each of the n characters is read once and causes either one append or one delete at the end of kept, and neither moves other characters.
  • Space: O(n), because kept can hold every character when there are no stars, and toCharArray() makes one more copy of the input.

A related problem removes any k equal letters that end up side by side, for a number k it is given: see Remove All Adjacent Duplicates in String II.