Remove All Adjacent Duplicates in String II

Medium

Topics
StringStack

A k-duplicate removal deletes k adjacent equal characters from s, closing the gap so the characters either side become neighbours.

Repeat k-duplicate removals until no more are possible, and return the final string. The answer is unique — the order of removals does not change it.

Example 1

sd0e1e2e3d4b5b6c7c8c9b10d11a12a13
answeraa
survivesremoved by some k-run
A run of 3 equal neighbours is deleted, and the deletion makes the characters either side of it neighbours in turn — so removals cascade. Here 12 characters disappear, leaving aa. The final answer does not depend on the order the removals are done in.
One cell per character; the small numbers underneath are indices.
Input:  s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: Remove eee and ccc to get ddbbbdaa, then bbb to get dddaa, then ddd to get aa.

Example 2

sp0b1b2c3g4g5t6t7c8i9i10i11p12p13o14o15a16a17i18s19
answerps
survivesremoved by some k-run
Input:  s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Explanation: Each pair collapses and the collapse exposes the next pair, all the way down to ps.

Example 3

sa0b1c2d3
answerabcd
survives
No run of 2 ever forms here, so nothing is removed.
Input:  s = "abcd", k = 2
Output: "abcd"
Explanation: No two adjacent characters are equal, so nothing is removed.

Constraints

  • 1 <= s.length <= 10^5
  • 2 <= k <= 10^4
  • s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

Scanning the string and restarting after each removal is correct and quadratic, because a removal in the middle can expose a new run and the scan begins again from the left.

What makes one pass enough is noticing where a new run can appear. Collapsing a run joins its two neighbours, and those neighbours are the character just before the run and the character just after it. So the only place a new run can form is at the boundary — and the character before the run is the one most recently kept.

That makes the structure a stack of (character, run length) pairs. Each incoming character either extends the run on top or starts a new one, and when a run reaches k it is discarded, which immediately re-exposes the run beneath it as the new top. No rescanning, and the string is rebuilt once at the end.

Approach

  1. Keep a stack of pairs: a character and how many times it currently repeats.
  2. For each character of s: if it equals the character on top, increase that count; otherwise push a new pair with count 1.
  3. If the top count reaches k, pop the pair. Whatever was below it becomes the top, so the next character is compared against the right neighbour.
  4. Rebuild the answer by writing each surviving character its recorded number of times, from the bottom of the stack up.

Walkthrough

s = "deeedbbcccbdaa", k = 3

char   stack (char x count)
  d    d1
  e    d1 e1
  e    d1 e2
  e    d1 e3  -> reaches 3, pop   ->  d1
  d    d2
  b    d2 b1
  b    d2 b2
  c    d2 b2 c1
  c    d2 b2 c2
  c    d2 b2 c3 -> pop            ->  d2 b2
  b    d2 b3    -> pop            ->  d2
  d    d3       -> pop            ->  (empty)
  a    a1
  a    a2

surviving: a x 2  ->  "aa"

Notice the cascade: popping ccc exposed bb, which the next
b completed, which exposed dd, which the next d completed.

Complexity

  • Time — O(n): each character is pushed once and contributes to at most one pop. The restart-on-removal version is O(n^2 / k).
  • Space — O(n): the stack, in the worst case one entry per character.

Common Pitfalls

  • Storing individual characters rather than runs with counts. It works, and the equality test then has to look back k positions instead of one.
  • Checking for the count reaching k only when a new character arrives. The check belongs immediately after the increment, so the cascade fires at the right moment.
  • Rebuilding the string inside the loop. That reintroduces the quadratic cost the stack removed.
  • Comparing against the character before the current one in the original string rather than the top of the stack. After a removal those are different characters.

Full Solution — all languages

class Solution:
    def removeDuplicates(self, s, k):
        stack = []
        for c in s:
            if stack and stack[-1][0] == c:
                stack[-1][1] += 1
                if stack[-1][1] == k:
                    stack.pop()
            else:
                stack.append([c, 1])
        return "".join(c * count for c, count in stack)
SensAI
Beta
Tap the mic to stop voice mode