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 - Stack Approach INPUT Input String s: ( ) idx 0 idx 1 Valid Bracket Pairs: ( ) { } [ ] Stack (LIFO): Push open brackets Pop to match close brackets ALGORITHM STEPS 1 Initialize Stack Create empty stack 2 Process char '(' Open bracket: Push to stack ( stack: ['('] 3 Process char ')' Close bracket: Check match ( = ) Match! Pop '(' from stack 4 Check Stack Stack empty? Return true Empty stack: [] Time: O(n) | Space: O(n) n = length of string FINAL RESULT Processing Complete: 1. Read '(' --> Push Stack: ['('] 2. Read ')' --> Pop + Match Stack: [] 3. Stack empty = Valid! Output: true OK - All brackets matched! Input: s = "()" Output: true Key Insight: Use a stack to track open brackets. When you encounter a closing bracket, check if it matches the most recent open bracket (top of stack). If all brackets match and stack is empty at end, string is valid. Stack ensures correct order: last opened must be first closed (LIFO property). TutorialsPoint - Valid Parentheses | Optimal Stack Solution
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