Minimum String Length After Removing Substrings — LeetCode 2696 Python Solution

EasyStackStringSimulation
Problem
#2696
Pattern
Stack
Reading time
2 min

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

Python
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) - 1

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview