Remove All Adjacent Duplicates In String Problem
Description
LeetCode Problem 1047.
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
Input: s = "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Example 2:
Input: s = "azxxzy"
Output: "ay"
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters.
Solution
Approach: Stack
Removing a pair can bring two equal letters next to each other ("abba" → "aa" → ""), so repeatedly scanning the string could take O(n2) time. A stack handles the chain reaction in one pass.
Read the string left to right and keep the already-reduced prefix on a stack:
- If the next letter equals the top of the stack, the two form a pair: pop the top and drop the letter.
- Otherwise push the letter.
After a pop, the new top is exactly the letter that now sits next to whatever comes after, so cascading removals are handled automatically. The stack, read bottom to top, is the final string. The problem says the result is unique, so the order in which pairs are removed does not matter.
Complexity: O(n) time and O(n) space.
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = [] # the reduced prefix read so far
for c in s:
if stack and stack[-1] == c:
stack.pop() # c cancels the letter before it
else:
stack.append(c)
return ''.join(stack)