Remove All Adjacent Duplicates In String - Problem
Imagine you have a string of lowercase letters, and you have a special power: whenever you see two identical letters sitting next to each other, you can make them both disappear instantly! ๐จ
Your mission is to repeatedly use this power until there are no more adjacent duplicate pairs left. The fascinating thing is that removing one pair might create new adjacent duplicates elsewhere in the string.
Goal: Return the final string after all possible adjacent duplicate removals have been made.
Example: "abbaca" โ Remove "bb" โ "aaca" โ Remove "aa" โ "ca"
Note: The answer is guaranteed to be unique!
Input & Output
example_1.py โ Basic Adjacent Duplicates
$
Input:
s = "abbaca"
โบ
Output:
"ca"
๐ก Note:
First remove 'bb' โ 'aaca', then remove 'aa' โ 'ca'. No more adjacent duplicates remain.
example_2.py โ Cascading Removal
$
Input:
s = "azxxzy"
โบ
Output:
"ay"
๐ก Note:
Remove 'xx' โ 'azzy', then remove 'zz' โ 'ay'. The removal of one pair creates a new adjacent pair.
example_3.py โ No Duplicates
$
Input:
s = "abc"
โบ
Output:
"abc"
๐ก Note:
No adjacent duplicate characters exist, so the string remains unchanged.
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- The answer is guaranteed to be unique
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Start with an empty stack and process string left to right
2
Push Rule
If stack is empty or top differs from current char, push current char
3
Pop Rule
If stack top equals current char, pop (both chars cancel out)
4
Result
Final stack contents form the answer
Key Takeaway
๐ฏ Key Insight: The stack automatically handles cascading removals - when we pop a duplicate pair, the previous character (now on top) might match the next character we process!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code