Remove All Adjacent Duplicates in String II
LeetCode 1209 · Medium · solution, intuition & step-by-step walkthrough
Stack of [char, count]; pop at count k.
This is how I solved Remove All Adjacent Duplicates in String II (LeetCode 1209), a medium problem from the Stack Simulation / String Processing pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Keep a stack of (character, run length). A matching character extends the top run; when a run reaches k it disappears, which may bring two runs of the same character together on the next push.
Approach
- 1
New character → push with count 1.
- 2
Same as top → increment; at k, pop.
- 3
Rebuild from the stack.
How I solved it
Run-length stackPythonO(n) time
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack =[]
for char in s:
if len(stack)==0 or stack[-1]["char"]!=char:
stack.append({"char":char,"count":1})
else:
stack[-1]["count"]+=1
if stack[-1]["count"]==k:
stack.pop()
res =""
for item in stack:
res+=item["char"]*item["count"]
return res
Remove All Adjacent Duplicates in String II — FAQ
What is the intuition behind Remove All Adjacent Duplicates in String II?
Keep a stack of (character, run length). A matching character extends the top run; when a run reaches k it disappears, which may bring two runs of the same character together on the next push.
How do you solve Remove All Adjacent Duplicates in String II (LeetCode 1209)?
1. New character → push with count 1. 2. Same as top → increment; at k, pop. 3. Rebuild from the stack.
What is the time and space complexity of Remove All Adjacent Duplicates in String II?
Time: O(n). Space: O(n). (Accepted approach: Run-length stack.)
What are common mistakes in Remove All Adjacent Duplicates in String II?
Rebuilding with += in a loop is fine here; ''.join is faster for big inputs.