Remove All Adjacent Duplicates in String II (LeetCode 1209): Solution and Explanation

Medium
String
Stack

Delete any run of k equal adjacent letters, let the two sides join, and repeat until nothing more can go. For deeedbbcccbdaa with k = 3 the answer is aa.

Intuition

Deleting a run and rescanning the whole string from the start works, but it can take a quadratic number of steps on long inputs.

When a run disappears, only the letter just left of the gap can join with what comes next. That letter is the most recent survivor, which is the top of a stack.

Storing single letters on the stack would force you to count backwards to see whether a run reached k. Store each run once as a [letter, count] pair instead, so the check is a single comparison on the top.

Approach: Stack of [letter, count] pairs

  1. Create an empty stack of pairs.
  2. For each letter ch: if the top pair has the same letter, increment its count; otherwise push [ch, 1].
  3. If the top count now equals k, pop the pair. The run is gone and the pair below is exposed for the next letter.
  4. At the end, write each pair's letter count times, from bottom to top.

Step-by-step example

s = "deeedbbcccbdaa", k = 3
  1. Push [d,1], then e three times builds [e,3], which equals k and is popped. The top is [d,1] again.
  2. The next d joins it: [d,2].
  3. b, b make [b,2]. Then c three times builds [c,3] and it is popped.
  4. The next b joins [b,2] to make [b,3], which is popped. The top is [d,2].
  5. The next d makes [d,3], which is popped. The stack is empty.
  6. a, a give [a,2]. Expanding it gives aa, the answer.

Code: Python, Java, C++

1class Solution:
2    def removeDuplicates(self, s: str, k: int) -> str:
3        stack = []  # [char, count]
4        for ch in s:
5            if stack and stack[-1][0] == ch:
6                stack[-1][1] += 1
7            else:
8                stack.append([ch, 1])
9            if stack[-1][1] == k:
10                stack.pop()
11        return "".join(c * n for c, n in stack)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each letter causes one push or one increment and at most one pop, and the final expansion writes at most n letters.

Space

O(n)

In the worst case no two neighbours match and every letter is its own pair on the stack.

Other approaches

Repeated scan and delete (time O(n^2 / k), space O(n))

Scan for a run of k, delete it, and start again until a full scan removes nothing. Simple but each pass is linear and there can be about n / k passes.

Two pointers with a count array (time O(n), space O(n))

Overwrite the character array in place with a write pointer, and keep count[j] = length of the run ending at position j. When count reaches k, move the write pointer back by k.

Common mistakes

  • Pushing single letters and then checking the last k entries every time, which makes the pass O(n * k).
  • Forgetting that a pop can expose a pair with the same letter as the next character. The next letter must increment that exposed pair, not start a new one.
  • Expanding the stack from top to bottom, which reverses the answer. In Java an ArrayDeque used with push and pop needs pollLast to read bottom first.

Frequently asked questions

Why store counts instead of letters?

With counts, checking whether the newest run reached k is one comparison on the top pair. With single letters you would have to look back k positions on every step.

Why is the order of removals irrelevant?

The problem guarantees the final string is unique. The stack removes each run as soon as it is complete, which is one valid order, so it reaches that unique answer.

How does this relate to the first version of the problem?

Remove All Adjacent Duplicates in String is the special case k = 2, where a plain stack of letters is enough because a pair is complete as soon as the top matches.

What happens when k is larger than any run?

No pair ever reaches k, nothing is popped, and the stack simply rebuilds the original string.