Remove All Adjacent Duplicates In String

EasyStack · String🧩 StackLeetCode #1047 ↗Updated

Problem

You have a string s of lowercase letters. A move deletes two neighbouring, equal letters; the pieces on either side then join up and may form a new equal pair. Keep making moves until none is possible and return the final string (it is always unique).
Inputs = "abbaca"Output"ca" (drop "bb" → "aaca", drop "aa" → "ca")
Inputs = "azxxzy"Output"ay"
Inputs = "aa"Output""

1 ≤ s.length ≤ 105  ·  s consists of lowercase English letters

Try it yourself

Java
class Solution {
    public String removeDuplicates(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A new letter can only cancel with the last surviving letter to its left. Keep the survivors on a stack: if the incoming letter equals the top, pop (they annihilate); otherwise push. One pass does all the chained removals.
PatternStack

Instinct Things resolve in reverse order of arrival (brackets, adjacent pairs, nested expressions) - push now, pop when its partner shows up.

Memory hack Last in, first out - like a pile of plates, you only ever touch the one on top; every closer pops its opener.

Open the Stack guide →

Approaches

Brute ForceRepeated Scan & Delete

Time O(n2)Space O(n)

Literally simulate the moves: scan for any adjacent equal pair, delete it, and restart the scan one position earlier (the deletion may have created a new pair there). Each deletion shifts the rest of the buffer, so up to n/2 deletions cost O(n) each.

Java
public String removeDuplicates(String s) {
    StringBuilder sb = new StringBuilder(s);
    int i = 0;
    while (i + 1 < sb.length()) {
        if (sb.charAt(i) == sb.charAt(i + 1)) {
            sb.delete(i, i + 2);      // O(n) shift
            i = Math.max(0, i - 1);   // a new pair may now touch i-1
        } else {
            i++;
        }
    }
    return sb.toString();
}

Faithful to the statement, but quadratic on inputs like "abccba...".

At a glance

LevelApproachTimeSpace
Brute ForceRepeated Scan & DeleteO(n2)O(n)
BetterExplicit Stack of CharactersO(n)O(n)
OptimalIn-place Write Pointer (char[] as Stack)O(n)O(n)
Common pitfalls
  • Deleting a pair and continuing from the same index — misses the newly formed pair to the left.
  • Popping the Deque in push order — returns the survivors reversed.
  • Assuming a whole run of equal letters vanishes — only pairs cancel, so "aaa" leaves "a".
Interview tips
  • Notice the removals are like matching brackets — that suggests a stack.
  • Argue the result is order-independent, so a greedy left-to-right pass is safe.
  • Offer the char-array version to show you can avoid boxing.
Pattern
Cancel-with-top stack → adjacent elements annihilate or merge, with chain reactions.
My notes saved in this browser