Remove All Adjacent Duplicates in String II
mediumTime: O(n)Space: O(n)
Signals to notice
remove adjacent groups of k identical charactersgeneralized from pairs to groups of kstack with counts
Brute force first
Repeatedly scan and remove — O(n²/k).
The key insight
Stack of (char, count). Push chars, increment if same as top. When count = k, pop. O(n).
What must stay true
The (char, count) stack tracks consecutive identical characters. Removal at k automatically exposes new adjacencies.
Easy way to go wrong
Not tracking counts — plain char stack requires recounting after each removal.