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

  1. Use a stack-based approach
  2. Push if top != current
  3. 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

  1. Inspect the current stack top.
  2. Pop on an equal neighbor.
  3. 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 all Strings exercises · Run this idea in the Java compiler