You are given a string s and an integer k, a kduplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make kduplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Problem summary: You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Stack
Example 1
"abcd"
2
Example 2
"deeedbbcccbdaa"
3
Example 3
"pbbcggttciiippooaais"
2
Related Problems
Remove All Adjacent Duplicates In String (remove-all-adjacent-duplicates-in-string)
Replace Non-Coprime Numbers in Array (replace-non-coprime-numbers-in-array)
Minimize String Length (minimize-string-length)
Step 02
Core Insight
What unlocks the optimal approach
Use a stack to store the characters, when there are k same characters, delete them.
To make it more efficient, use a pair to store the value and the count of each character.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1209: Remove All Adjacent Duplicates in String II
class Solution {
public String removeDuplicates(String s, int k) {
Deque<int[]> stk = new ArrayDeque<>();
for (int i = 0; i < s.length(); ++i) {
int j = s.charAt(i) - 'a';
if (!stk.isEmpty() && stk.peek()[0] == j) {
stk.peek()[1] = (stk.peek()[1] + 1) % k;
if (stk.peek()[1] == 0) {
stk.pop();
}
} else {
stk.push(new int[] {j, 1});
}
}
StringBuilder ans = new StringBuilder();
for (var e : stk) {
char c = (char) (e[0] + 'a');
for (int i = 0; i < e[1]; ++i) {
ans.append(c);
}
}
ans.reverse();
return ans.toString();
}
}
// Accepted solution for LeetCode #1209: Remove All Adjacent Duplicates in String II
func removeDuplicates(s string, k int) string {
stk := []pair{}
for _, c := range s {
if len(stk) > 0 && stk[len(stk)-1].c == c {
stk[len(stk)-1].v = (stk[len(stk)-1].v + 1) % k
if stk[len(stk)-1].v == 0 {
stk = stk[:len(stk)-1]
}
} else {
stk = append(stk, pair{c, 1})
}
}
ans := []rune{}
for _, e := range stk {
for i := 0; i < e.v; i++ {
ans = append(ans, e.c)
}
}
return string(ans)
}
type pair struct {
c rune
v int
}
# Accepted solution for LeetCode #1209: Remove All Adjacent Duplicates in String II
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
t = []
i, n = 0, len(s)
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
cnt = j - i
cnt %= k
if t and t[-1][0] == s[i]:
t[-1][1] = (t[-1][1] + cnt) % k
if t[-1][1] == 0:
t.pop()
elif cnt:
t.append([s[i], cnt])
i = j
ans = [c * v for c, v in t]
return "".join(ans)
// Accepted solution for LeetCode #1209: Remove All Adjacent Duplicates in String II
impl Solution {
pub fn remove_duplicates(s: String, k: i32) -> String {
let mut stack: Vec<(char, usize)> = vec![];
for ch in s.chars() {
if !stack.is_empty() && stack.last().unwrap().0 == ch {
let mut last = stack.pop().unwrap();
last.1 += 1;
stack.push(last);
} else {
stack.push((ch, 1));
}
if stack.last().unwrap().1 == k as usize {
stack.pop();
}
}
stack.iter().fold(String::new(), |acc, &(ch, count)| {
acc + &ch.to_string().repeat(count)
})
}
}
// Accepted solution for LeetCode #1209: Remove All Adjacent Duplicates in String II
function removeDuplicates(s: string, k: number): string {
const stack: { char: string; count: number }[] = []; // [char, count];
for (const c of s) {
if (stack.length !== 0 && stack[stack.length - 1].char === c) {
stack[stack.length - 1].count++;
} else {
stack.push({ char: c, count: 1 });
}
if (stack[stack.length - 1].count === k) {
stack.pop();
}
}
return stack.reduce(
(acc, { char, count }) => (acc += char.repeat(count)),
''
);
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
MONOTONIC STACK
O(n) time
O(n) space
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.