Skip to content

Valid Parentheses

Given a string s containing just the characters '(', ')', '[', ']', '{' and '}', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of closing bracket.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.
InputValid?Explanation
"()"trueSimple pair of parentheses
"()[]{}"trueThree different pairs, all properly closed
"(]"falseClosing bracket does not match opening bracket
"([{}])"trueNested brackets in correct order
"([)]"falseBrackets closed in wrong order (interleaved)
""trueEmpty string is valid
"("falseUnclosed opening bracket
")"falseClosing bracket with no opening
  • 0 <= s.length <= 10^4
  • s consists of parentheses only: '(', ')', '[', ']', '{', '}'
ApproachTimeSpaceIntuitionBest When
StackO(n)O(n)Process left-to-right, match using memoryGeneral case — fast and clear
Replace LoopO(n²)O(n)Remove pairs repeatedlyLearning the concept, simple implementation
  • Pick Stack if you want the best all-around solution.
  • Pick Replace Loop if you want to understand the concept through a brute-force lens.
Recommended
Stack
O(n) time · O(n) space
Intuitive
Replace Loop
O(n²) time · O(n) space
★ Recommended

Use a stack to track opening brackets. When you encounter a closing bracket, check if it matches the most recent opening bracket on the stack.

Key insight: The last opened bracket that hasn’t been closed yet must match the current closing bracket. This is exactly what a stack provides — last-in-first-out (LIFO) access.

⏱ Time O(n) Single pass 💾 Space O(n) Stack in worst case

Input: s = "([{}])"

StepCharStack (before)ActionStack (after)
1([]Opening bracket → push['(']
2[['(']Opening bracket → push['(', '[']
3{['(', '[']Opening bracket → push['(', '[', '{']
4}['(', '[', '{']Closing bracket → top is { → match! pop['(', '[']
5]['(', '[']Closing bracket → top is [ → match! pop['(']
6)['(']Closing bracket → top is ( → match! pop[]
End[]Stack empty → valid ✓

Input: s = "([)]"

StepCharStack (before)ActionResult
1([]Opening bracket → push['(']
2[['(']Opening bracket → push['(', '[']
3)['(', '[']Closing bracket → top is [, but we see ) → no match! ✗Invalid

Animated walkthrough

How the stack solution validates parentheses

Watch the stack grow and shrink as opening brackets are pushed and closing brackets are matched and popped.

Step 1 of 7
Waiting to begin...
Array state
Memory / lookup state

function validParenthesesStack(s):
stack = []
bracketMap = {'(': ')', '[': ']', '{': '}'}
for char in s:
if char is an opening bracket:
stack.push(char)
else:
if stack is empty or bracketMap[stack.pop()] != char:
return false
return stack is empty
valid_parentheses_stack.py
from typing import List
def valid_parentheses_stack(s: str) -> bool:
"""
Check if parentheses are balanced using a stack.
Approach: Use a stack to match closing brackets with opening brackets.
- Push opening brackets onto the stack
- For each closing bracket, check if it matches the top of the stack
- At the end, the stack should be empty
Time: O(n) - single pass through the string
Space: O(n) - stack size in worst case (all opening brackets)
"""
stack = []
bracket_map = {'(': ')', '[': ']', '{': '}'}
for char in s:
if char in bracket_map:
# Opening bracket - push to stack
stack.append(char)
else:
# Closing bracket - check if it matches
if not stack or bracket_map[stack.pop()] != char:
return False
# Stack should be empty (all brackets matched)
return len(stack) == 0
if __name__ == "__main__":
# Test cases
print(valid_parentheses_stack("()")) # True
print(valid_parentheses_stack("()[]{}")) # True
print(valid_parentheses_stack("(]")) # False
print(valid_parentheses_stack("([])")) # True
print(valid_parentheses_stack("{[]}")) # True
print(valid_parentheses_stack("")) # True
print(valid_parentheses_stack("(")) # False
print(valid_parentheses_stack(")")) # False
✓ Simple

Repeatedly remove consecutive pairs of matching brackets until no more can be removed. If the string becomes empty, it is valid.

This approach is conceptually simpler but less efficient. It directly models the idea that valid brackets always have matching pairs next to each other.

⏱ Time O(n²) Multiple passes 💾 Space O(n) Temporary strings

Input: s = "([{}])"

PassCurrent StringPairs RemovedNext String
1"([{}])"{}"([])"
2"([])"[]"()"
3"()"()""
End""Valid ✓

Input: s = "([)]"

PassCurrent StringPairs RemovedNext String
1"([)]""([)]"
End"([)]"No pairs to removeInvalid ✗
function validParenthesesReplace(s):
while s contains "()" or "[]" or "{}":
remove all occurrences of "()", "[]", "{}"
return s is empty
valid_parentheses_replace.py
def valid_parentheses_replace(s: str) -> bool:
"""
Check if parentheses are balanced by repeatedly removing matched pairs.
Approach: Repeatedly remove consecutive pairs of matching brackets
until either the string is empty (valid) or no more pairs can be removed (invalid).
Time: O(n²) - each pass removes at least 2 characters, up to n/2 passes
Space: O(n) - for temporary string during replacement
Note: This approach is simple to understand but slower than stack.
"""
while "()" in s or "[]" in s or "{}" in s:
s = s.replace("()", "").replace("[]", "").replace("{}", "")
return len(s) == 0
if __name__ == "__main__":
# Test cases
print(valid_parentheses_replace("()")) # True
print(valid_parentheses_replace("()[]{}")) # True
print(valid_parentheses_replace("(]")) # False
print(valid_parentheses_replace("([])")) # True
print(valid_parentheses_replace("{[]}")) # True
print(valid_parentheses_replace("")) # True
print(valid_parentheses_replace("(")) # False
print(valid_parentheses_replace(")")) # False
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
valid_parentheses_space_optimized.py
"""
Solution for Valid Parentheses
"""
def solve():
"""Implementation for approach 3 of Valid Parentheses"""
pass
if __name__ == "__main__":
print("Solution ready")