Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: open brackets are closed by the same type of brackets, open brackets are closed in the correct order, and every close bracket has a corresponding open bracket of the same type.
- 1 <= s.length <= 10⁴
- s consists of parentheses only: ()[]{}
- A valid string always has even length (every open needs one close)
s = "()"trues = "()[]{}"trues = "{[()]}"trues = "(]"falseWhen you need to ensure that every opening bracket is closed in the correct order, a beginner might first try to just count the brackets. If there are three '(' and three ')', it is valid, right?
Wrong! Consider the string ([)]. The counts are perfect, but the logic is broken. Brackets are like nested boxes: if you open a large box '(' and then a small box '[', you must close the small box before you can even touch the large one. This strict nesting means only the most recently opened bracket matters at any given moment.
This is why we need a Stack. A Stack is a Last-In, First-Out (LIFO) data structure. It acts like a temporary memory that only remembers the very last promise you made.
- Making a Promise: Every time you see an opening bracket ('(', '[', '{'), you are making a promise to close it later. You Push this promise onto the Stack.
- Fulfilling a Promise: When you see a closing bracket (')', ']', '}'), you are checking the most recent promise you made. You Pop the top of the Stack.
- If the brackets match (e.g., you see a ')' and the top of the Stack is '('), the promise is fulfilled!
- If they do not match, or the Stack is empty (meaning you are trying to close a box you never opened), the string is invalid.
- The Final Audit: Once you have scanned the whole string, the Stack must be completely empty. If there is a promise left over, it means you opened a box and forgot to close it.
stack = []
bracket_map = { ')': '(', ']': '[', '}': '{' }
FOR each character in string:
IF character is an OPENING bracket:
stack.PUSH(character)
ELSE (it's a CLOSING bracket):
IF stack is empty OR stack.POP() != bracket_map[character]:
RETURN False (Invalid Order)
RETURN stack.IS_EMPTY (Valid only if all closed)Last-In-First-Out Verification
Start with an empty stack.
A stack naturally ensures that the most recently opened context is the first to be closed.