Remove Adjacent Duplicates in Java: Solution, Explanation & Practice
Remove adjacent duplicate characters
Problem summary
Remove all adjacent duplicate characters repeatedly until no more can be removed.
Starter code
public class Main {
public static void main(String[] args) {
String str = "abbaca"; // Test case 1
// Remove adjacent duplicates
// Print: <result>
}
}Expected output and test cases
- abbaca → aaca → ca
ca
- No adjacent duplicates
abc
- All removed: aabbcc
Hints
- Use a stack-based approach
- Push if top != current
- Pop if top == current
Validated solution
Reveal Java solution
public class Main {
static String removePairs(String text) {
StringBuilder stack = new StringBuilder();
for (char ch : text.toCharArray()) {
int top = stack.length() - 1;
if (top >= 0 && stack.charAt(top) == ch) stack.deleteCharAt(top);
else stack.append(ch);
}
return stack.toString();
}
public static void main(String[] args) {
System.out.println(removePairs("abbaca"));
}
}How to approach the problem
Treat StringBuilder as a stack. A new character cancels the top only when they match; otherwise it becomes the new top. That local cancellation automatically exposes pairs created by an earlier removal.
Approach
- Inspect the current stack top.
- Pop on an equal neighbor.
- Push otherwise.
Time and space complexity
Time: O(n). Space: O(n).
Edge cases to test
- An empty input remains empty.
- Cascading removals such as abbaca are the reason a single replace call is insufficient.
Common mistakes
- Removing pairs only once and missing newly adjacent pairs.
- Reading the top of an empty builder.
Follow-up challenge
Remove groups of k adjacent equal characters instead of pairs.
Related Strings exercises
- Practice String Compression in Java
- Practice Alphabetical Character Frequency in Java
- Practice Zigzag Conversion in Java
Practice all Strings exercises · Run this idea in the Java compiler