Valid Parentheses - Problem
Imagine you're reading a complex mathematical expression or code snippet - how do you know if all the brackets are properly matched? This classic problem asks you to determine if a string of brackets is valid.
Given a string s containing only parentheses (), square brackets [], and curly braces {}, determine if the input string is valid.
A string is considered valid if:
- Every opening bracket has a corresponding closing bracket of the same type
- Brackets are closed in the correct order (Last In, First Out - LIFO)
- Every closing bracket matches the most recent unmatched opening bracket
Examples:
"()"→ Valid ✅"()[]{}"→ Valid ✅"([)]"→ Invalid ❌ (wrong order)"(("→ Invalid ❌ (unmatched opening)
Input & Output
example_1.py — Basic Valid Case
$
Input:
s = "()"
›
Output:
true
💡 Note:
The string contains a single pair of parentheses that are properly matched and in correct order.
example_2.py — Multiple Types Valid
$
Input:
s = "()[]{}"
›
Output:
true
💡 Note:
All three types of brackets are present and each pair is properly matched in the correct order.
example_3.py — Invalid Order
$
Input:
s = "([)]"
›
Output:
false
💡 Note:
Although each opening bracket has a corresponding closing bracket, they are not in the correct order. The ']' closes before ')' but '[' was opened after '('.
Constraints
- 1 ≤ s.length ≤ 104
-
s consists of parentheses only:
'()[]{}' - Follow-up: Can you solve this in O(1) space? (Hint: It's not possible while maintaining O(n) time)
Visualization
Tap to expand
Understanding the Visualization
1
Opening Bracket = Add Plate
When we see '(', '[', or '{', we add it to our stack like adding a plate
2
Closing Bracket = Remove Plate
When we see ')', ']', or '}', we check the top plate and remove it if it matches
3
Validation Check
If plates don't match or stack is empty when we try to remove, it's invalid
4
Final State
Valid parentheses leave us with an empty stack - all plates were properly paired!
Key Takeaway
🎯 Key Insight: Valid parentheses follow LIFO order - exactly what a stack provides. Each closing bracket must match the most recently opened bracket, making stack the perfect data structure for this problem!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code