Remove All Adjacent Duplicates In String
Use a stack (or string accumulator) — push or pop based on the top.
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#
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; }};func removeDuplicates(s string) string { st := make([]byte, 0, len(s)) for i := 0; i < len(s); i++ { c := s[i] if len(st) > 0 && st[len(st)-1] == c { st = st[:len(st)-1] } else { st = append(st, c) } } return string(st)}class Solution: def removeDuplicates(self, s: str) -> str: st: list[str] = [] for c in s: if st and st[-1] == c: st.pop() else: st.append(c) return ''.join(st)function removeDuplicates(s) { const st = []; for (const c of s) { if (st.length > 0 && st[st.length - 1] === c) st.pop(); else st.push(c); } return st.join('');}class Solution { public String removeDuplicates(String s) { StringBuilder st = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int len = st.length(); if (len > 0 && st.charAt(len - 1) == c) { st.deleteCharAt(len - 1); } else { st.append(c); } } return st.toString(); }}function removeDuplicates(s: string): string { const st: string[] = []; for (const c of s) { if (st.length > 0 && st[st.length - 1] === c) st.pop(); else st.push(c); } return st.join('');}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#
Related#