Practice › Stack & Queue
Remove Adjacent Duplicates
Easy · Stack & Queue · Asked at Amazon, Meta, Microsoft, TCS, Infosys
Repeatedly delete two adjacent equal letters from the string until no such pair remains. Print the final string, or EMPTY if nothing is left.
The final string is the same whichever pairs you delete first.
Input
A single line with a string of lowercase letters.
Output
The final string, or EMPTY.
Constraints
- 1 ≤ length ≤ 10^5
Use the result as a stack: if the next letter equals the top, pop it; otherwise push it.
Example 1
Input
abbaca
Output
ca
Example 2
Input
azxxzy
Output
ay
Hints
- Deleting a pair can bring two new equal letters next to each other ("abba" → "aa" → "").
- Process left to right and keep the letters that survive so far.
- If the next letter equals the last kept one, they cancel.
Approach
Use the answer string itself as a stack. For each letter: if it equals the top of the stack, pop (the pair disappears); otherwise push it. Whatever remains is the final string. Every letter is pushed and popped at most once, so repeated rescans are never needed.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, st;
cin >> s;
for (char c : s) {
if (!st.empty() && st.back() == c) st.pop_back();
else st.push_back(c);
}
cout << (st.empty() ? "EMPTY" : st) << "\n";
return 0;
}Python solution
s = input().strip()
st = []
for c in s:
if st and st[-1] == c:
st.pop()
else:
st.append(c)
print("".join(st) if st else "EMPTY")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
StringBuilder st = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int len = st.length();
if (len > 0 && st.charAt(len - 1) == c) st.deleteCharAt(len - 1);
else st.append(c);
}
System.out.println(st.length() == 0 ? "EMPTY" : st.toString());
}
}Solve Remove Adjacent Duplicates online · All practice problems