Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Validate parenthesesE02. Reverse a string using a stackE03. Implement a stack with push, pop, and peekE

Problem No 1

Validate parentheses

Easy

6 minute session

Summary

Check whether a string of brackets is balanced and properly nested using a stack.

Problem statement

Given a string containing characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1) Open brackets are closed by the same type of brackets. 2) Open brackets are closed in the correct order. 3) An empty string is considered valid. Use a stack to verify the correctness efficiently.

Task

Implement a function that returns True if the input string contains valid matching pairs of parentheses, brackets, and braces; otherwise False.

Examples

Simple balanced

Input

validate_parentheses('([{}])')

Output

True

Explanation

All opening brackets are matched in the correct order with corresponding closing brackets.

Input format

A single string s containing only the characters '(', ')', '{', '}', '[' and ']'. Example: '([{}])'

Output format

Return True if s is valid, otherwise return False.

Constraints

0 <= len(s) <= 10^4; only the six bracket characters appear.

Samples

Sample input 0

validate_parentheses('()')

Sample output 0

True

Explanation 0

A simple matching pair is valid.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.