Introduction
The Remove Adjacent Duplicates problem involves removing consecutive duplicate characters from a string.
Given a string s, the task is to:
- repeatedly remove adjacent duplicate characters
- until no duplicates remain
This problem is an important application of:
Stack Data StructureThis problem helps in understanding:
- stacks
- string processing
- duplicate removal
- traversal techniques
Example
Input:s = "abbaca"
Output:
"ca"
Explanation: Remove: bb
String becomes: "aaca"
Remove: aa
Final string: "ca"
Input:
s = "azxxzy"
Output:
"ay"
Explanation: Remove:
xx
String becomes: "azzy"
Remove: zz
Final string: "ay"
Constraints
1 <= s.length <= 10^5s contains lowercase English lettersApproach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse string repeatedly
- Remove adjacent duplicates
- Continue until no duplicates remain
This approach works but repeated string rebuilding increases time complexity.
Steps
- Traverse string.
- Detect adjacent duplicates.
- Remove duplicate pair.
- Restart traversal.
- Continue until no duplicates remain.
Dry Run
Input:s = "abbaca"
Check: bb Remove duplicates
String becomes: "aaca"
Check: aa
Remove duplicates
String becomes: "ca"
No duplicates remain
Final Result: "ca"
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:Repeated traversal and rebuilding of string is performed. Space Complexity: O(n)
Explanation: Extra string storage is used.
Approach 2 : Optimized Solution (Stack)
Explanation
The optimized solution uses a Stack.
The idea is:
- Traverse characters one by one
- Compare current character
with stack top - If same:
- remove duplicate
- Otherwise:
- push character
This efficiently removes adjacent duplicates in one traversal.
Steps
- Create empty stack.
- Traverse string characters.
- Compare with stack top.
- Remove duplicates if same.
- Otherwise push character.
- Build final string.
Dry Run
Input:s = "abbaca"
Traverse a:
Push into stack
Stack: a
Traverse b: Push into stack
Stack: a b
Traverse b: Duplicate found
Pop b
Stack: a
Traverse a: Duplicate found
Pop a
Stack: empty
Continue traversal...
Final Result: "ca"
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation:Each character is processed once.
Space Complexity: O(n)
Explanation:
Extra stack is used.
Edge Cases