#1209
Medium Algorithms Remove all adjacent duplicates in string ii
String Stack
60.9% acceptance
Feb 25, 2026
6063
124
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn remove_duplicates(s: String, k: i32) -> String {
let k = k as usize;
// stack stores (char, count)
let mut stack: Vec<(char, usize)> = Vec::new();
for c in s.chars() {
if let Some(last) = stack.last_mut() {
if last.0 == c {
last.1 += 1;
if last.1 == k {
stack.pop();
}
continue;
}
}
stack.push((c, 1));
}
let mut result = String::new();
for (c, cnt) in stack {
for _ in 0..cnt {
result.push(c);
}
}
result
}
}