Leetcode 2696. Minimum String Length After Removing Substrings
You are given a string s
consisting of lowercase English letters. You need to repeatedly delete two adjacent characters in that string if they are either “AB” or “CD” and return the minimum possible length of the resulting string.
Before we start solving the problem, it’s critical to clarify a few points:
The problem can be approached using a stack. The stack-based approach works effectively here because it allows us to track characters and remove adjacent pairs efficiently.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int minLengthAfterRemovingSubstrings(string s) {
stack<char> stk;
for (char ch : s) {
if (!stk.empty() && (
(stk.top() == 'A' && ch == 'B') ||
(stk.top() == 'C' && ch == 'D'))) {
stk.pop();
} else {
stk.push(ch);
}
}
return stk.size();
}
int main() {
string s;
cin >> s; // Input string can be taken from the user
cout << minLengthAfterRemovingSubstrings(s) << endl; // Displays the result
return 0;
}
The time complexity of the proposed solution is O(n), where n
is the length of the string. This is because each character is processed exactly once, and stack operations (push and pop) are O(1).
The space complexity is also O(n) in the worst case where no pairs are removed, and all characters are stored in the stack.
This approach ensures that we can efficiently determine the minimum length of the string after repeatedly removing the substrings “AB” and “CD”. By leveraging a stack, we handle the adjacency and pairing conditions effectively, ensuring optimal time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?