Minimum String Length After Removing Substrings - Problem
Problem: You are given a string
Goal: Return the minimum possible length of the resulting string after all possible removals.
Important: After removing a substring, the remaining parts concatenate and may form new
Example: For string
s consisting only of uppercase English letters. Your task is to repeatedly remove occurrences of the substrings "AB" or "CD" from the string until no more such substrings exist.Goal: Return the minimum possible length of the resulting string after all possible removals.
Important: After removing a substring, the remaining parts concatenate and may form new
"AB" or "CD" substrings that can be removed in subsequent operations.Example: For string
"ABFCDB", we can remove "AB" to get "FCDB", then remove "CD" to get "FB". The final length is 2. Input & Output
example_1.py โ Basic Removal
$
Input:
s = "ABFCDB"
โบ
Output:
2
๐ก Note:
We can remove 'AB' to get 'FCDB', then remove 'CD' to get 'FB'. No more removals possible, so final length is 2.
example_2.py โ Multiple Cascading Removals
$
Input:
s = "ACBDCD"
โบ
Output:
2
๐ก Note:
First remove 'CD' to get 'ACBD', then we can remove 'CB' (no, wait - only AB and CD can be removed). Actually, we remove 'CD' to get 'ACBD', no further removals possible. Length is 4. Let me recalculate: Remove 'CD' -> 'ACB' + 'D' = 'ACBD'. No AB or CD found. Wait, that's wrong. Let me trace: 'ACBDCD' - we can remove the last 'CD' to get 'ACBD', but we're looking for 'AB' or 'CD' only. Actually 'ACBD' has no removable substrings. But if we had 'ACDBCD', removing first 'CD' gives 'ABCD', then 'AB' gives 'CD', then 'CD' gives ''. Let me use a proper example.
example_2.py โ Multiple Cascading Removals
$
Input:
s = "ACDBCD"
โบ
Output:
0
๐ก Note:
Remove 'CD' to get 'ABCD', then remove 'AB' to get 'CD', finally remove 'CD' to get empty string. Length is 0.
example_3.py โ No Removals Possible
$
Input:
s = "CXABY"
โบ
Output:
5
๐ก Note:
The string contains no 'AB' or 'CD' substrings that can be removed, so the length remains 5.
Constraints
- 1 โค s.length โค 100
- s consists only of uppercase English letters
-
Only substrings
'AB'and'CD'can be removed
Visualization
Tap to expand
Understanding the Visualization
1
Start with Empty Stack
Begin processing the string with an empty stack representing the final result
2
Process Each Character
For each character, decide whether to add it or remove a previous character
3
Check for Removable Pairs
If current character forms 'AB' or 'CD' with stack top, remove the pair
4
Build Final Result
Characters remaining in stack represent the minimum length string
Key Takeaway
๐ฏ Key Insight: The stack naturally handles the 'last-in, first-out' behavior needed when removals create new adjacent pairs that can also be removed!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code