Skip to main content
Back to problems
Leetcode
Medium
Stacks
Strings
Greedy
Minimum String Length After Removing Substrings

Repeatedly remove occurrences of fixed substrings until none remain, and return the final string length.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Remove All Occurrences of a Substring

gfg
Problem Statement

Problem

You are given a string s made up of uppercase English letters. In one operation, you may remove any occurrence of either substring "AB" or "CD" from the string.

Keep performing this operation as long as possible. Return the minimum possible length of the string after all valid removals have been made.

The order of characters that remain must stay the same relative to each other; only whole matching substrings can be deleted.

Goal

Find the length of the shortest string obtainable after repeatedly deleting "AB" and "CD" wherever they appear.

Input Format

  • A single string s consisting of uppercase English letters.
  • You may assume the only removable substrings are "AB" and "CD".

Output Format

  • Return a single integer: the minimum final length of the string after all possible removals.

Constraints

  • 1 <= s.length <= 100
  • s contains only uppercase English letters.
  • Only adjacent pairs "AB" and "CD" may be removed.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "ABFCACDB"

Output

2

Explanation

One valid sequence is: remove AB -> FCACDB, remove CD -> FCAB, remove AB -> FC. The final length is 2.

Example 2

Input

s = "ACBBD"

Output

5

Explanation

No substring AB or CD appears, so nothing can be removed.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.