Valid Parentheses
Problem Statement
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets, and Open brackets must be closed in the correct order.
Constraints:
- 1 <= s.length <= 10^4
- s consists of parentheses only '()[]{}'.
Input Format:
- A string s containing just the characters '(', ')', '{', '}', '[' and ']'
Output Format:
- Return true if the input string is valid, otherwise return false.
Examples:
Example 1:
Input:
s = "()"
Output:
true
Explanation:
The parentheses in the string form a valid pair.
Example 2:
Input:
s = "()[]{}"
Output:
true
Explanation:
All the brackets in the string form valid pairs and are closed in the correct order.
Example 3:
Input:
s = "(]"
Output:
false
Explanation:
The bracket types don't match ('(' and ']').
Example 4:
Input:
s = "([)]"
Output:
false
Explanation:
The brackets aren't closed in the correct order.
Example 5:
Input:
s = "{[]}"
Output:
true
Explanation:
All the brackets form valid pairs and are closed in the correct order.
Solutions
Stack Approach
Use a stack to keep track of opening brackets. When a closing bracket is encountered, check if it matches the top of the stack.
Algorithm Walkthrough
Example input:
Step-by-step execution:
- s = "({[]})"
- Initialize empty stack
- Char '(': Push to stack -> stack = ['(']
- Char '{': Push to stack -> stack = ['(', '{']
- Char '[': Push to stack -> stack = ['(', '{', '[']
- Char ']': Matches top of stack '[', pop -> stack = ['(', '{']
- Char '}': Matches top of stack '{', pop -> stack = ['(']
- Char ')': Matches top of stack '(', pop -> stack = []
- Stack is empty at the end, return true
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the stack operations as each character is processed.
Key visualization elements:
- current character
- stack state
- matching brackets
Implementation Notes
This is a classic stack problem that demonstrates how stacks can efficiently solve bracket matching problems.