Minimum String Length After Removing Substrings (LeetCode 2696): Solution and Explanation

Easy
String
Stack
Simulation

You may delete any "AB" or "CD" from an uppercase string, as often as you like, and the pieces join after each deletion. Return the shortest length you can reach. "ABFCACDB" shrinks to "FC", so the answer is 2.

Intuition

Deleting a pair joins the letter just before it with the letter just after it, which can form a new pair. Simulating by searching the string again after each deletion works but repeats a lot of work.

Read the string left to right and keep the letters that have survived so far. The only letter a new character can pair with is the last survivor, which is the top of a stack.

The order of deletions does not matter here: A only pairs with a following B and C only with a following D, so pairs never compete for the same letter. Greedy cancelling on the stack is therefore optimal.

Approach: Stack of surviving letters

  1. Create an empty stack.
  2. For each letter ch: if the stack is not empty and the top plus ch is "AB" or "CD", pop the top. The pair is deleted.
  3. Otherwise push ch.
  4. Return the stack size.

Step-by-step example

s = "ABFCACDB"
  1. Push A. B meets A on top: AB is deleted. Stack empty.
  2. Push F, C, A, C. Stack FCAC.
  3. D meets C on top: CD is deleted. Stack FCA.
  4. B meets A on top: AB is deleted. Stack FC.
  5. The stack holds 2 letters, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def minLength(self, s: str) -> int:
3        stack = []
4        for ch in s:
5            if stack and stack[-1] + ch in ("AB", "CD"):
6                stack.pop()
7            else:
8                stack.append(ch)
9        return len(stack)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each letter is pushed at most once and popped at most once.

Space

O(n)

A string with no removable pairs keeps every letter on the stack.

Other approaches

Repeated replace (time O(n^2), space O(n))

While the string contains AB or CD, replace them with the empty string. Each pass is linear and there can be up to n / 2 passes. Fine for n = 100.

In-place write pointer (time O(n), space O(1) extra)

Use the character array itself as the stack with a write index. Overwrite or step back instead of pushing and popping, for O(1) extra space.

Common mistakes

  • Checking only adjacent pairs in the original string. In CABD the C and D only become neighbours after AB is deleted.
  • Treating BA or DC as removable. Only AB and CD in that order count.
  • Comparing against the previous character of s instead of the top of the stack. After a deletion the relevant neighbour is the last surviving letter.

Frequently asked questions

Can a different order of deletions give a shorter string?

No. Every B can only pair with an A and every D with a C, and the stack pairs each closing letter with the nearest unmatched opening letter, just like matching brackets. Every valid sequence of deletions removes the same pairs.

Is this the same as matching parentheses?

Very close. Think of A and C as two kinds of opening bracket and B and D as their closers. Other letters act as walls that nothing can pair across, since they never get removed.

How does it compare to Remove All Adjacent Duplicates In String?

Same stack pattern, different cancel rule. There a letter cancels an equal letter on top; here B cancels A and D cancels C.