Remove All Adjacent Duplicates in String II
Master this topic with zero to advance depth.
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
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.
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).
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.