Minimum String Length After Removing Substrings - 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.

Return the minimum possible length of the resulting string that you can obtain.

Note that the string concatenates after removing the substring and could produce new "AB" or "CD" substrings.

Input & Output

Example 1 — Multiple Removals
$ Input: s = "ABFCACDB"
Output: 2
💡 Note: Remove "AB" → "FCACDB", then remove "CD" → "FCAB", then remove "AB" → "FC". Final length is 2.
Example 2 — Complete Removal
$ Input: s = "ACBDCD"
Output: 4
💡 Note: Remove "CD" → "ACBD". No more "AB" or "CD" patterns exist, so no further operations can be performed. Final length is 4.
Example 3 — No Removals Possible
$ Input: s = "ACBD"
Output: 4
💡 Note: No "AB" or "CD" substrings exist, so no operations can be performed. Final length is 4.

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists only of uppercase English letters

Visualization

Tap to expand
Minimum String Length After Removing Substrings INPUT String s = "ABFCACDB" A B F C A C D B 0 1 2 3 4 5 6 7 Removable Patterns: "AB" "CD" Use write pointer (w) to track valid chars char[] arr = s.toCharArray() w = 0 (write index) Iterate and check ALGORITHM STEPS 1 Initialize Convert to char array, w=0 2 Process Each Char Place at arr[w], then w++ 3 Check Pattern If AB or CD formed, w-- 4 Return w Final w = min length Simulation: i=0: A --> arr=[A], w=1 i=1: B, AB found! w=0 i=2: F --> arr=[F], w=1 i=3: C --> arr=[F,C], w=2 i=4: A --> arr=[F,C,A], w=3 i=5: C --> arr=[F,C,A,C], w=4 i=6: D, CD found! w=3 i=7: B, AB found! w=2 FINAL RESULT After all removals: F C Output: 2 Remaining: "FC" Removal Chain: ABFCACDB Remove AB at start FCACDB Remove CD FCAB --> FC Remove AB (formed) Key Insight: Using in-place simulation with a write pointer (w), we avoid creating new strings. When we place a character and it forms "AB" or "CD" with the previous character, we simply decrement w (effectively removing the pair). This handles cascading removals naturally. Time: O(n), Space: O(n) for char array. TutorialsPoint - Minimum String Length After Removing Substrings | In-Place Character Array Simulation
Asked in
Meta 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen