DSA Stacks

Remove All Adjacent Duplicates In String

Use a stack (or string accumulator) — push or pop based on the top.

Easy
Time O(n) Space O(n)
LeetCode
2 min read
stack string

Problem#

Given a string s, repeatedly remove two adjacent equal characters until no such pair exists. Return the final string.

Examples#

  • "abbaca""ca"
  • "azxxzy""ay"

Constraints#

  • 1 <= s.length <= 10^5. Lowercase English letters.

Approach#

Treat a string as a stack. For each character, if it equals the top, pop; otherwise push.

Solution#

Remove All Adjacent Duplicates In String
class Solution {
public:
string removeDuplicates(string s) {
string st;
st.reserve(s.size());
for (char c : s) {
if (!st.empty() && st.back() == c) st.pop_back();
else st.push_back(c);
}
return st;
}
};

Editorial#

Each character is pushed at most once and popped at most once — total work is O(n). The stack representation collapses cascading duplicates naturally because removing the top exposes the previous character for the next iteration.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.