Minimum String Length After Removing Substrings (LeetCode 2696): Solution and Explanation
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
- Create an empty stack.
- For each letter
ch: if the stack is not empty and the top pluschis"AB"or"CD", pop the top. The pair is deleted. - Otherwise push
ch. - Return the stack size.
Step-by-step example
s = "ABFCACDB"
- Push
A.BmeetsAon top:ABis deleted. Stack empty. - Push
F,C,A,C. StackFCAC. DmeetsCon top:CDis deleted. StackFCA.BmeetsAon top:ABis deleted. StackFC.- 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)1class Solution {
2 public int minLength(String s) {
3 StringBuilder stack = new StringBuilder();
4 for (char ch : s.toCharArray()) {
5 int n = stack.length();
6 if (n > 0 && ((stack.charAt(n - 1) == 'A' && ch == 'B') || (stack.charAt(n - 1) == 'C' && ch == 'D'))) {
7 stack.deleteCharAt(n - 1);
8 } else {
9 stack.append(ch);
10 }
11 }
12 return stack.length();
13 }
14}1class Solution {
2public:
3 int minLength(string s) {
4 string stack;
5 for (char ch : s) {
6 if (!stack.empty() && ((stack.back() == 'A' && ch == 'B') || (stack.back() == 'C' && ch == 'D'))) {
7 stack.pop_back();
8 } else {
9 stack.push_back(ch);
10 }
11 }
12 return stack.size();
13 }
14};Time and space complexity
O(n)
Each letter is pushed at most once and popped at most once.
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
CABDtheCandDonly become neighbours afterABis deleted. - Treating
BAorDCas removable. OnlyABandCDin that order count. - Comparing against the previous character of
sinstead 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.