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
The Magic Stack CancellationString: "abbaca"abbacaMagic StackBottomTopcaFinal: "ca"Step-by-Step Process1Process 'a': Stack empty โ†’ Push 'a'2Process 'b': Top โ‰  'b' โ†’ Push 'b'3Process 'b': Top = 'b' โ†’ POP! (Cancel out)4Process 'a': Top = 'a' โ†’ POP! (Cancel out)5Process 'c': Stack empty โ†’ Push 'c'6Process 'a': Top โ‰  'a' โ†’ Push 'a'
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!
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
87.5K Views
High Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen