Remove All Adjacent Duplicates in String II

Remove every group of k equal letters standing together, including the groups that form after earlier removals, in one pass with a stack of letter counts.

You are given a string s and a number k. Whenever k equal letters stand next to each other, remove them, and the letters on either side close the gap. Keep doing this until no k equal letters stand together, and return what is left. The order in which you remove groups does not change the final string.

Example 1
Input: s = "abcd", k = 2
Output: "abcd"
Example 2
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Example 3
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"

In Example 1 no two neighbours are equal, so nothing is removed. Example 2 is the interesting one. Removing "eee" and "ccc" leaves "ddbbbdaa". Now three b's stand together, which they did not before, so "bbb" goes too, leaving "dddaa". That brings three d's together, and removing them leaves "aa". One removal can create the next one.

The simple way, and why it is slow

The direct way is to do what the problem says: scan the string for k equal neighbours, remove them, and scan again from the start, until a scan finds nothing. For Example 2 that takes 5 scans: four that each remove a group, and one that finds nothing left to remove.

Each scan reads the whole string, and there can be up to n / k removals for a string of n letters, so the total work grows like n × n / k, written O(n² / k). For 100,000 letters and k = 2 that is billions of steps. The slow part is going back to the start after every removal, when only the letters around the gap have changed.

Reading once and remembering runs

Instead of rescanning, read the string once, from left to right, and keep the letters that survive so far. Keep them grouped into runs: a run is a group of equal letters standing together, such as "bb", stored as the letter and its count, b ×2.

A new letter can only ever join the last run, never an earlier one. So the runs belong on a stack, a pile where you only add to the top, look at the top, or remove from the top. For each letter:

  • If it is the same letter as the top run, add 1 to that run's count. If the count reaches k, remove the run from the stack.
  • Otherwise, put a new run with a count of 1 on top.

Removing a run is what makes the chain of removals work. When a run is removed, the run underneath becomes the top again, with its count still remembered. If the next letter matches it, its count simply carries on. That is exactly the gap closing in the problem, without going back to the start.

Walking through Example 2

The stack of runs while reading deeedbbcccbdaa with k = 3. After d e e e, the run e×3 is removed and d×1 remains. After d b b c c c, c×3 is removed and d×2, b×2 remain. After b, b×3 is removed and d×2 remains. After d, d×3 is removed and the stack is empty. After a a, a×2 remains, so the answer is aa.

The picture shows the stack for s = "deeedbbcccbdaa" and k = 3, with the bottom of the stack at the bottom. Each column shows the letters read in that step and the stack after them. An orange box is a run that reached 3 and was removed.

Look at the first column. The d starts a run d ×1. The three e's build a run e ×3, which reaches 3 and is removed, so d ×1 is on top again.

In the second column, the next d matches the top run, so it becomes d ×2, continuing the d from before the e's. Then the b's make b ×2, and the c's make c ×3, which is removed.

Now the chain reaction. In the third column, the next letter is a b, and the top run is b ×2 again, so it reaches 3 and is removed. In the fourth column, a d makes d ×2 reach 3, and the stack is empty. Finally the two a's make a ×2, which is all that is left: the answer is "aa".

Java Solution

The method keeps each run as a two-element array, {letter, count}, on an ArrayDeque, Java's usual stack class. Its main method runs the three examples and one more input, "aaaa" with k = 2, where every letter is removed.

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

public class RemoveAllAdjacentDuplicatesInStringII {

    public static String removeDuplicates(String s, int k) {
        Deque<int[]> stack = new ArrayDeque<>();      // each run is {letter, count}
        for (char c : s.toCharArray()) {
            if (!stack.isEmpty() && stack.peek()[0] == c) {
                if (++stack.peek()[1] == k) {         // the top run grows by one
                    stack.pop();                      // k in a row: remove the run
                }
            } else {
                stack.push(new int[] {c, 1});         // a new run of one letter
            }
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            int[] run = stack.pollLast();             // the bottom run comes first in the string
            result.append(String.valueOf((char) run[0]).repeat(run[1]));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println("\"" + removeDuplicates("abcd", 2) + "\"");
        System.out.println("\"" + removeDuplicates("deeedbbcccbdaa", 3) + "\"");
        System.out.println("\"" + removeDuplicates("pbbcggttciiippooaais", 2) + "\"");
        System.out.println("\"" + removeDuplicates("aaaa", 2) + "\"");   // everything removed
    }
}

Running it prints:

Output
"abcd"
"aa"
"ps"
""

The first three lines match the examples. Look at the last line: for "aaaa" the run reaches 2 and is removed, then the next two a's do the same, so the stack ends empty and the result is the empty string.

Two lines in the code are worth a closer look. ++stack.peek()[1] adds 1 to the count of the top run without taking it off the stack: peek() returns the array itself, so changing it changes the run on the stack. And the result is rebuilt with pollLast(), which takes runs from the bottom of the stack, where the start of the string is. Taking them from the top with pop() or pollFirst() would write the runs backwards: "abcd" would come out as "dcba".

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

Complexity

  • Time: O(n). Each of the n letters is handled once, with one push, one count update or one removal, and rebuilding the result writes at most n letters.
  • Space: O(n). The stack holds one run per letter when no two neighbours are equal, as in "abcd". toCharArray() also makes a copy of the n letters.

For the simplest form of this idea, where each new character removes the one on top of the stack, see Removing Stars From a String.