Minimum String Length After Removing Substrings
Push characters; when the top with the current forms "AB" or "CD", pop instead — return final length.
3 min read
stack string
Problem#
You can repeatedly delete any occurrence of "AB" or "CD" from a string. Return the minimum possible length after these deletions.
Examples#
"ABFCACDB"→2"ACBBD"→5
Constraints#
1 <= s.length <= 100, uppercase English letters.
Approach#
Stack-based collapse. Push each character; if the last two characters now form "AB" or "CD", pop both.
Solution#
class Solution {public: int minLength(string s) { string st; st.reserve(s.size()); for (char c : s) { if (!st.empty() && ((st.back() == 'A' && c == 'B') || (st.back() == 'C' && c == 'D'))) { st.pop_back(); } else { st.push_back(c); } } return st.size(); }};func minLength(s string) int { st := make([]byte, 0, len(s)) for i := 0; i < len(s); i++ { c := s[i] if len(st) > 0 { top := st[len(st)-1] if (top == 'A' && c == 'B') || (top == 'C' && c == 'D') { st = st[:len(st)-1] continue } } st = append(st, c) } return len(st)}class Solution: def minLength(self, s: str) -> int: st: list[str] = [] for c in s: if st and ((st[-1] == 'A' and c == 'B') or (st[-1] == 'C' and c == 'D')): st.pop() else: st.append(c) return len(st)function minLength(s) { const st = []; for (const c of s) { const top = st[st.length - 1]; if (st.length && ((top === 'A' && c === 'B') || (top === 'C' && c === 'D'))) { st.pop(); } else { st.push(c); } } return st.length;}class Solution { public int minLength(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) { char top = st.charAt(len - 1); if ((top == 'A' && c == 'B') || (top == 'C' && c == 'D')) { st.deleteCharAt(len - 1); continue; } } st.append(c); } return st.length(); }}function minLength(s: string): number { const st: string[] = []; for (const c of s) { const top = st[st.length - 1]; if (st.length && ((top === 'A' && c === 'B') || (top === 'C' && c === 'D'))) { st.pop(); } else { st.push(c); } } return st.length;}Editorial#
Each removal can expose a new collapsible pair behind it — exactly what a stack tracks. The order of deletion doesn’t matter for the final length because the operations are confluent.
Complexity#
- Time: O(n).
- Space: O(n).
Concept revision#
Related#