#1047
Remove All Adjacent Duplicates In String
EasyStringStackStackGreedy Algorithm
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a stack allows us to efficiently manage the characters as we process the string. When we encounter a character, we check if it matches the top of the stack. If it does, we pop the stack (remove the duplicate); if not, we push the character onto the stack. This way, we only traverse the string once.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty stack.
- 2Step 2: Loop through each character in the string.
- 3Step 3: If the stack is not empty and the top of the stack equals the current character, pop the stack.
- 4Step 4: If they are not equal, push the current character onto the stack.
- 5Step 5: After processing all characters, join the stack to form the final string.
solution.py8 lines
1def removeDuplicates(s):
2 stack = []
3 for char in s:
4 if stack and stack[-1] == char:
5 stack.pop()
6 else:
7 stack.append(char)
8 return ''.join(stack)ℹ
Complexity note: The time complexity is linear because we traverse the string once, and the space complexity is also linear due to the stack potentially holding all characters in the worst case.
- 1Using a stack helps manage duplicates efficiently.
- 2The problem can be solved in a single pass with a stack.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.