Minimum String Length After Balanced Removals

medium string stack counting

Problem

You are given a string s of only 'a' and 'b'. You may repeatedly remove any substring that contains an equal number of 'a' and 'b' characters; the surrounding parts then join together. Return the minimum possible length after any number of such removals.

Because an 'a' and a 'b' together form a balanced (removable) pair, every pairing can be cancelled. Process the characters with a stack: if the current character is the opposite of the stack's top, pop it (cancel a pair); otherwise push. What survives is just the surplus of whichever letter is more common, so the answer equals abs(count_a − count_b).

Inputs = "aaabb"
Output1
Remove "ab" to get "aab", remove "ab" again to get "a". One leftover 'a' remains, so the length is 1.

def minLengthAfterRemovals(s):
    stack = []
    for ch in s:
        if stack and stack[-1] != ch:
            stack.pop()          # cancel a balanced a-b pair
        else:
            stack.append(ch)     # nothing to cancel; keep it
    return len(stack)            # == abs(count_a - count_b)
function minLengthAfterRemovals(s) {
  const stack = [];
  for (const ch of s) {
    if (stack.length && stack[stack.length - 1] !== ch) {
      stack.pop();               // cancel a balanced a-b pair
    } else {
      stack.push(ch);            // nothing to cancel; keep it
    }
  }
  return stack.length;           // == abs(countA - countB)
}
int minLengthAfterRemovals(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char ch : s.toCharArray()) {
        if (!stack.isEmpty() && stack.peek() != ch) {
            stack.pop();         // cancel a balanced a-b pair
        } else {
            stack.push(ch);      // nothing to cancel; keep it
        }
    }
    return stack.size();         // == abs(countA - countB)
}
int minLengthAfterRemovals(string s) {
    vector<char> stack;
    for (char ch : s) {
        if (!stack.empty() && stack.back() != ch) {
            stack.pop_back();    // cancel a balanced a-b pair
        } else {
            stack.push_back(ch); // nothing to cancel; keep it
        }
    }
    return (int)stack.size();    // == abs(countA - countB)
}
Time: O(n) Space: O(n)