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 a and z), remove both.
  • Otherwise, add the current character to the stack.

Algorithm

  1. Create an ans string to act as a stack.
  2. Iterate through each character c in s.
  3. Check whether ans.back() and c are adjacent:
  4. abs(ans.back() - c) == 1
  5. abs(ans.back() - c) == 25 (circular adjacency: a and z).
  6. If adjacent, remove the stack top using pop_back().
  7. Otherwise, push c into ans.
  8. 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.