Remove All Adjacent Duplicates in String II
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
Remove All Adjacent Duplicates in String II
Repeatedly remove
k adjacent and equal characters from string s until no more such removals are possible.Visual Representation
s = "deeedbbcccbdaa", k = 3
1. Process 'd': Stack [(d, 1)]
2. Process 'e': Stack [(d, 1), (e, 1)]
3. Process 'e': Stack [(d, 1), (e, 2)]
4. Process 'e': Stack [(d, 1), (e, 3)] -> Count=3! Pop (e).
5. Process 'd': Stack [(d, 2)]
...
Result: "aa"Examples
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Approach 1
Level I: Brute Force (Repeated Removal)
Intuition
Repeatedly scan the string, looking for any group of k consecutive identical characters. When found, remove them and restart the scan. Repeat until no more groups of k are found. This is slow but conceptually simple.
⏱ O(N^2 / k) — Each scan is O(N) and each removal reduces the string by k characters.💾 O(N) for the working string.
Approach 2
Level III: Optimal (Stack of Char-Count Pairs)
Intuition
Use a stack to keep track of characters and their contiguous counts. When the next character matches the top of the stack, increment the top's count. If it matches
k, pop it. If it doesn't match, push a new pair (char, 1).⏱ O(N)💾 O(N)
Detailed Dry Run
| Char | Action | Stack (Top Pair) | Length |
|---|---|---|---|
| 'd' | Push | (d, 1) | 1 |
| 'e' | Push | (e, 1) | 2 |
| 'e' | Incr | (e, 2) | 2 |
| 'e' | Pop | - | 1 |
⚠️ Common Pitfalls & Tips
Ensure the stack stores pairs so you don't have to pop characters one by one. Rebuilding the string efficiently at the end is also key.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.