Valid Parentheses - Problem

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.

Input & Output

Example 1 — Valid Nested
$ Input: s = "()"
Output: true
💡 Note: Simple pair: opening parenthesis followed by closing parenthesis
Example 2 — Mixed Valid
$ Input: s = "()[{}]"
Output: true
💡 Note: All brackets properly matched: () pair, then [{}] where {} is nested inside []
Example 3 — Invalid Order
$ Input: s = "(]"
Output: false
💡 Note: Mismatched types: opening parenthesis ( cannot be closed by square bracket ]

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of parentheses only '()[]{}'.

Visualization

Tap to expand
Valid Parentheses Problem OverviewValid Examples"()" "[]{}" "([{}])"Invalid Examples"(]" "([)]" ")(("Rules1. Same type matches2. Correct order (LIFO)Output: true (valid) or false (invalid)
Understanding the Visualization
1
Input
String containing only bracket characters
2
Process
Check if brackets are properly paired and nested
3
Output
Return true if valid, false otherwise
Key Takeaway
🎯 Key Insight: Use a stack to track opening brackets and match them with closing brackets in LIFO order
Asked in
Google 85 Amazon 92 Microsoft 78 Facebook 65
553.7K Views
Very High Frequency
~15 min Avg. Time
18.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen