Remove All Adjacent Duplicates in String
You are given a string consisting of lowercase letters. Repeatedly remove two adjacent duplicate characters until no more adjacent duplicates exist. Return the final string.
A stack makes this trivial: iterate through each character. If the stack is not empty and the top of the stack equals the current character, pop the stack (removing the pair). Otherwise, push the character onto the stack. At the end, the stack contains the remaining characters in order.
For example, "abbaca" → push a, push b, b matches top b → pop b, stack=[a], push a, a matches top a → pop a, stack=[], push c, push a → result = "ca".
Example Input & Output
bb is a pair → removed. Then aa becomes adjacent and is removed.
bb is removed. Then aa becomes adjacent and is removed. Empty result.
Single character, no duplicates.
xx is removed. Then zz becomes adjacent and is removed.
Algorithm Flow

Solution Approach
Create a stack (array). Iterate through each character. If the stack is not empty and the top equals the current character, pop. Otherwise, push. Join the stack at the end.
Time complexity is O(n). Space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public String solution(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (!stack.isEmpty() && stack.peek() == ch) stack.pop();
else stack.push(ch);
}
StringBuilder sb = new StringBuilder();
for (char ch : stack) sb.append(ch);
return sb.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
