3561 - Resulting String After Adjacent Removals
Pattern: Stack
Intuition
- Use a stack to simulate adjacent character removals.
- If the current character and stack top are adjacent alphabetically (including
aandz), remove both. - Otherwise, add the current character to the stack.
Algorithm
- Create an
ansstring to act as a stack. - Iterate through each character
cins. - Check whether
ans.back()andcare adjacent: abs(ans.back() - c) == 1abs(ans.back() - c) == 25(circular adjacency:aandz).- If adjacent, remove the stack top using
pop_back(). - Otherwise, push
cintoans. - Return
ans.
C++ Code
class Solution {
public:
string resultingString(string s) {
string ans;
for (char c : s) {
if (!ans.empty() &&
(abs(ans.back() - c) == 1 ||
abs(ans.back() - c) == 25)) {
ans.pop_back();
} else {
ans.push_back(c);
}
}
return ans;
}
};
Complexity
Let N be the length of the string.
- Time Complexity:
O(N)— Each character is pushed and popped at most once. - Auxiliary Space Complexity:
O(N)— Stack can store up to N characters.
Key Takeaway: Stack naturally handles cascading removals because removing a pair can create a new adjacent pair.