Remove All Adjacent Duplicates in String II
Medium
Topics
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
aa. The final answer does not depend on the order the removals are done in.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
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
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
- Keep a stack of pairs: a character and how many times it currently repeats.
- For each character of
s: if it equals the character on top, increase that count; otherwise push a new pair with count 1. - 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. - 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
konly 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)import java.util.*;
class Solution {
public String removeDuplicates(String s, int k) {
Deque<int[]> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (!stack.isEmpty() && stack.peek()[0] == c) {
stack.peek()[1]++;
if (stack.peek()[1] == k) stack.pop();
} else {
stack.push(new int[]{c, 1});
}
}
StringBuilder out = new StringBuilder();
for (int[] pair : stack) {
for (int i = 0; i < pair[1]; i++) out.append((char) pair[0]);
}
return out.reverse().toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string removeDuplicates(string s, int k) {
vector<pair<char, int>> stack;
for (char c : s) {
if (!stack.empty() && stack.back().first == c) {
stack.back().second++;
if (stack.back().second == k) stack.pop_back();
} else {
stack.push_back({c, 1});
}
}
string out;
for (auto& pair_ : stack) out.append(pair_.second, pair_.first);
return out;
}
};/**
* @param {string} s
* @param {number} k
* @return {string}
*/ var removeDuplicates = function(s, k) {
const stack = [];
for (const c of s) {
if (stack.length && stack[stack.length - 1][0] === c) {
stack[stack.length - 1][1]++;
if (stack[stack.length - 1][1] === k) stack.pop();
} else {
stack.push([c, 1]);
}
}
return stack.map(pair => pair[0].repeat(pair[1])).join("");
};