Minimum String Length After Removing Substrings
Here’s a Python solution that uses a stackbased approach. The stack is used to track the characters in the string. If a ‘B’ or ‘D’ is encountered and the top of the stack contains ‘A’ or ‘C’ respectively, it means we can remove the substring and we pop the character from the stack. If not, we just add the character into the stack.


The code checks each character in the string. If the character is ‘B’ or ‘D’, we check the top of the stack (the last character we saw). If the last character was ‘A’ or ‘C’ respectively, we can remove the ‘AB’ or ‘CD’ substring, so we pop the character from the stack. Otherwise, we can’t remove a substring, so we just add the character to the stack. At the end, the size of the stack is the minimum possible length of the string after all possible removals.
Q&A
Is the stack approach the optimal solution?
Yes, the stack approach is optimal for this problem. It works in a single pass over the string (O(n) time complexity, where n is the length of the string), and it doesn’t require any extra space other than the stack (which in the worst case scenario is O(n), if all characters are different from ‘B’ and ‘D’, or if ‘B’ and ‘D’ always appear without a preceding ‘A’ or ‘C’).
The reason why it’s optimal is that it efficiently identifies and removes the ‘AB’ and ‘CD’ substrings as it encounters them. By using a stack, it ensures that it’s always dealing with the most recent characters, which enables it to handle cases where removing one substring creates a new one. So, this method not only determines whether a substring can be removed, but also carries out the removal in the same pass.
If we tried to solve this problem with other methods like repeatedly scanning the string for substrings or using dynamic programming, we would likely end up with a solution that is more complex and less efficient.