Remove All Adjacent Duplicates in String II - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abccba", k = 2
›
Output:
"ccba"
💡 Note:
We can remove "ab" leaving "ccba". No more k=2 adjacent duplicates exist.
Example 2 — Multiple Removals
$
Input:
s = "abbbaaca", k = 3
›
Output:
"ca"
💡 Note:
First remove "bbb" → "abaaca", then remove "aaa" → "ca". No more k=3 adjacent duplicates.
Example 3 — No Removals
$
Input:
s = "aa", k = 3
›
Output:
"aa"
💡 Note:
No groups of 3 consecutive identical characters exist, so string remains unchanged.
Constraints
- 1 ≤ s.length ≤ 105
- 2 ≤ k ≤ 104
- s only contains lower case English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with potential k-duplicate groups
2
Process
Remove groups of k consecutive identical characters
3
Output
Final string after all removals
Key Takeaway
🎯 Key Insight: Use a stack to track characters and their consecutive counts for efficient k-duplicate removal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code