DSA Stacks

Minimum String Length After Removing Substrings

Push characters; when the top with the current forms "AB" or "CD", pop instead — return final length.

Easy
Time O(n) Space O(n)
LeetCode
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#

Minimum String Length After Removing Substrings
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();
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.