Remove All Adjacent Duplicates In String
Easy
Topics
Given a string s, repeatedly remove two adjacent equal letters until no more can be removed. Return the final string.
Example 1
in
out
removed
A removal can expose a new adjacent pair, so one scan of the original string is not enough. A stack handles the cascade naturally: push each character unless it equals the top, in which case pop instead. What is left is
ca.Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "abbaca" Output: "ca"
Example 2
in
out
removed
Input: s = "azxxzy" Output: "ay"
Constraints
- 1 <= s.length <= 10^5
- s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Removing a pair can expose a new adjacent pair — "abba" loses bb, bringing the two as together, and they must go too. Rescanning the string after each removal is correct and O(n^2).
A stack collapses the cascade into one pass. Push each character, but first check whether it matches the current top; if it does, pop instead. The next character is then compared against the new top, which is the cascade handled automatically.
Approach
- For each character: if the stack is non-empty and its top equals the character, pop; otherwise push.
- Join the stack.
Dry Run
s = "abbaca"
a stack empty push [a]
b top a, differs push [a,b]
b top b, matches pop [a]
a top a, matches pop []
c stack empty push [c]
a top c, differs push [c,a]
answer "ca"
note the cascade: removing bb is what made the two a's
adjacent, and the stack caught it with no second passComplexity
- Time — O(n): each character pushed at most once and popped at most once. Against O(n^2) for repeated rescanning.
- Space — O(n): the stack, which holds the whole string when nothing cancels.
Common Pitfalls
- Popping without first checking the stack is non-empty.
- Rescanning from the start after each removal, which is the quadratic version.
- Removing all duplicates rather than adjacent pairs.
"aba"is unchanged — the twoas are not adjacent. - Deleting more than two at a time. The rule removes exactly a pair, so
"aaa"leaves onea, not none.
Full Solution — all languages
class Solution:
def removeDuplicates(self, s):
stack = []
for c in s:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
return "".join(stack)import java.util.*;
class Solution {
public String removeDuplicates(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) sb.deleteCharAt(sb.length() - 1);
else sb.append(c);
}
return sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string removeDuplicates(string s) {
string stack;
for (char c : s) {
if (!stack.empty() && stack.back() == c) stack.pop_back();
else stack.push_back(c);
}
return stack;
}
};/**
* @param {string} s
* @return {string}
*/ var removeDuplicates = function(s) {
const stack = [];
for (const c of s) {
if (stack.length && stack[stack.length - 1] === c) stack.pop();
else stack.push(c);
}
return stack.join('');
};
Asked at
Paytm