Algorithm Day70 - Valid Parentheses
🧩 Problem Description
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.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
💬 Examples
Example 1
1 | Input: s = "()" |
Example 2
1 | Input: s = "()[]{}" |
Example 3
1 | Input: s = "(]" |
Example 4
1 | Input: s = "([)]" |
Example 5
1 | Input: s = "{[]}" |
💡 Intuition
We can use a stack to track opening brackets:
- When encountering an opening bracket, push it onto the stack.
- When encountering a closing bracket, check if it matches the top of the stack.
- If not matched or stack is empty, return false.
- At the end, if the stack is empty, the string is valid.
🔢 Java Code (Stack)
1 | import java.util.*; |
⏱ Complexity Analysis
- Time: O(n) — each character processed once.
- Space: O(n) — in worst case stack holds all characters.
✍️ Summary
- Use stack to validate parentheses.
- Each closing bracket must match the latest opening bracket.
Related problems
lc-22
— Generate Parentheseslc-32
— Longest Valid Parentheses