Minimum String Length After Removing Substrings — LeetCode 2696 Python Solution
- Problem
- #2696
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "ABFCACDB"
- Output
- 2
- Explanation
- We can do the following operations:
Python solution
class Solution:
def minLength(self, s: str) -> int:
stk = [""]
for c in s:
if (c == "B" and stk[-1] == "A") or (c == "D" and stk[-1] == "C"):
stk.pop()
else:
stk.append(c)
return len(stk) - 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the string s auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2696. Minimum String Length After Removing Substrings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2696. Minimum String Length After Removing Substrings?
- LeetCode 2696. Minimum String Length After Removing Substrings is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2696. Minimum String Length After Removing Substrings?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2696. Minimum String Length After Removing Substrings?
- The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.
- What topics does LeetCode 2696. Minimum String Length After Removing Substrings cover?
- LeetCode 2696. Minimum String Length After Removing Substrings is tagged Stack, String and Simulation on LeetCode.