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 skkk
Example 1
Output: "abcd"
Example 2
Output: "aa"
Example 3
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
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
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
, remove the run from the stack.k - 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 picture shows the stack for s = "deeedbbcccbdaa"k = 3
Look at the first column. The d starts a run d ×1e ×3d ×1
In the second column, the next d matches the top run, so it becomes d ×2b ×2c ×3
Now the chain reaction. In the third column, the next letter is a b, and the top run is b ×2d ×2a ×2
Java Solution
The method keeps each run as a two-element array, {letter, count}ArrayDequemaink = 2
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:
"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]peek()pollLast()pop()pollFirst()
The original implementation,
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".
also makes a copy of the n letters.toCharArray()
For the simplest form of this idea, where each new character removes the one on top of the stack, see