Minimum String Length After Removing Substrings - Problem
You are given a string s consisting only of uppercase English letters.
You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings "AB" or "CD" from s.
Return the minimum possible length of the resulting string that you can obtain.
Note that the string concatenates after removing the substring and could produce new "AB" or "CD" substrings.
Input & Output
Example 1 — Multiple Removals
$
Input:
s = "ABFCACDB"
›
Output:
2
💡 Note:
Remove "AB" → "FCACDB", then remove "CD" → "FCAB", then remove "AB" → "FC". Final length is 2.
Example 2 — Complete Removal
$
Input:
s = "ACBDCD"
›
Output:
0
💡 Note:
Remove "CD" → "ACBD", then remove "AB" → "CD", then remove "CD" → "". Final length is 0.
Example 3 — No Removals Possible
$
Input:
s = "ACBD"
›
Output:
4
💡 Note:
No "AB" or "CD" substrings exist, so no operations can be performed. Final length is 4.
Constraints
- 1 ≤ s.length ≤ 100
- s consists only of uppercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Original string with removable patterns
2
Remove Patterns
AB and CD substrings are eliminated
3
Final Length
Count remaining characters
Key Takeaway
🎯 Key Insight: Use stack-like processing to immediately remove patterns as they form, avoiding multiple string scans
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code