Minimum String Length After Removing Substrings

You are given a string `s` of uppercase English letters. In one operation you may remove any occurrence of the substring `"AB"` or `"CD"`. The remaining parts join together, which can create new occurrences. Return the minimum possible length of the string after any number of operations.

30:00

Minimum String Length After Removing Substrings
easy
Free written solution
Topics
Companies

You are given a string s of uppercase English letters. In one operation you may remove any occurrence of the substring "AB" or "CD". The remaining parts join together, which can create new occurrences. Return the minimum possible length of the string after any number of operations.

Example 1:
Input: {"s":"ABFCACDB"}
Output: 2
Constraints:
  • 1≤s.length≤1001 \leq s.\text{length} \leq 100

  • s consists only of uppercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"ABFCACDB"}

s: letters with the same colour cancelled each other

A

0

B

1

F

2

C

3

A

4

C

5

D

6

B

7

Read s left to right onto a stack. Whenever the new letter completes "AB" or "CD" with the top of the stack, both vanish, and the letter below becomes the new top, ready to pair again.

stack (bottom → top), size 0

(empty)

no pairs removed yet

Variables
VariableValue
stack
DepthFunction Call
Stack empty
0/9