Remove All Adjacent Duplicates In String (LeetCode 1047): Solution and Explanation
Repeatedly delete two adjacent equal letters from s until no such pair remains, and return what is left. For abbaca the answer is ca.
Intuition
Deleting a pair can create a new pair. In abba, removing bb brings the two as together, and they cancel too. Rescanning the string after every removal works but can take quadratic time.
Read the string left to right and keep the letters that survive so far. A new letter can only form a pair with the last surviving letter, because everything before that is already free of pairs.
That last surviving letter is the top of a stack. If the new letter matches it, pop it and drop the new letter. If not, push the new letter. When a pop exposes an older letter, that letter is the top again, which handles the chain reactions for free.
Approach: Stack of kept letters
- Create an empty stack.
- For each letter
chofs: if the stack is not empty and its top equalsch, pop the top. - Otherwise push
ch. - Join the stack from bottom to top and return it.
Step-by-step example
s = "abbaca"
- Read
a. The stack is empty, so push it. Stack:a. - Read
b. It differs froma, so push it. Stack:ab. - Read
b. It equals the topb, so pop. Stack:a. - Read
a. It equals the topa, so pop. Stack is empty. - Read
cand push it, then readaand push it. Stack:ca. - Join the stack:
"ca".
Code: Python, Java, C++
1class Solution:
2 def removeDuplicates(self, s: str) -> str:
3 stack = []
4 for ch in s:
5 if stack and stack[-1] == ch:
6 stack.pop()
7 else:
8 stack.append(ch)
9 return "".join(stack)1class Solution {
2 public String removeDuplicates(String s) {
3 StringBuilder stack = new StringBuilder();
4 for (char ch : s.toCharArray()) {
5 int n = stack.length();
6 if (n > 0 && stack.charAt(n - 1) == ch) {
7 stack.deleteCharAt(n - 1);
8 } else {
9 stack.append(ch);
10 }
11 }
12 return stack.toString();
13 }
14}1class Solution {
2public:
3 string removeDuplicates(string s) {
4 string stack;
5 for (char ch : s) {
6 if (!stack.empty() && stack.back() == ch) {
7 stack.pop_back();
8 } else {
9 stack.push_back(ch);
10 }
11 }
12 return stack;
13 }
14};Time and space complexity
O(n)
Each letter is pushed at most once and popped at most once, and the final join is linear.
O(n)
In the worst case no letters cancel and the stack holds the whole string.
Other approaches
Two pointers in place (time O(n), space O(1) extra)
Use the string itself (as a character array) as the stack. A write pointer marks the top: copy each letter to the write position, and if it equals the letter just before, step the write pointer back by two. The answer is the prefix up to the write pointer.
Repeated scanning (time O(n^2), space O(n))
Scan for any adjacent equal pair, delete it, and start again until a scan finds nothing. Correct but slow: a string like abcddcba needs n/2 rescans.
Common mistakes
- Removing only the pairs visible in the original string. New pairs appear after a deletion, so a single pass that only compares s[i] with s[i+1] is wrong.
- Comparing with the previous letter of the input instead of the top of the stack. After a pop, the letter to compare with is the one below it.
- Building the answer by repeated string concatenation or deletion in a language with immutable strings. Use a list, StringBuilder or byte slice as the stack.
- Treating it like the k-duplicates version. Here exactly two letters cancel, so you do not need counts.
Frequently asked questions
Why is the answer unique?
Removals never interfere with each other in a way that changes the outcome. The stack scan applies them in one particular order and always reaches the same fully reduced string, which is the only string with no adjacent pair you can reach.
How does the stack handle chain reactions such as abba?
After b cancels b, the first a is on top of the stack again. The next a meets it immediately and cancels, so no rescan is needed.
How is this different from Remove All Adjacent Duplicates in String II?
In part II a run of k equal letters is removed. The stack then stores pairs of letter and count, and pops when the count reaches k.
What is the time complexity?
O(n) time and O(n) space with a stack, or O(1) extra space with the in-place two-pointer version.