Minimum Add to Make Parentheses Valid — stack
Push openers; a closer is legal only if it matches the current top. Built for LeetCode 921. Minimum Add to Make Parentheses Valid.
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 minimumAddToMakeParenthesesValid(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