Minimum String Length After Balanced Removals — stack
Push openers; a closer is legal only if it matches the current top. Built for LeetCode 3746. Minimum String Length After Balanced Removals.
The stack is the nest of brackets that are still open. A mismatch or a leftover opener at the end is an immediate no.
Algorithm
- On an opener, push.
- On a closer, the top must be its partner — otherwise reject.
- Return true only if the stack is empty at the end.
- Time
- O(n)
- Space
- O(n)
class Solution: def minimumStringLengthAfterBalancedRemovals(self, s: str) -> bool: pairs = {")": "(", "]": "[", "}": "{"} stack: list[str] = [] for ch in s: if ch in pairs: if not stack or stack[-1] != pairs[ch]: return False stack.pop() else: stack.append(ch) return not stack