Valid Parentheses
Valid Parentheses
Given a string containing only the characters '(', ')', '{', '}', '[', and ']', determine if the brackets are valid. A string is valid if: 1. Every opening bracket has a corresponding closing bracket of the same type. 2. Opening brackets are closed in the correct order (most recently opened must be closed first). 3. Every closing bracket matches the nearest unclosed opening bracket. Example: "()[]{}" → YES, "([)]" → NO, "{[]}" → YES
Input format — only if your code reads from stdin
Input format: - A single string of bracket characters (no spaces) Output: YES if the string is valid, NO otherwise.
Approach
Use a stack. Push every opening bracket. When you see a closing bracket, check if the stack is non-empty and its top is the matching opener — if not, print NO. At the end, the stack must be empty for the answer to be YES.
Input
Output
- •
1 ≤ len(s) ≤ 10^4
More Stacks problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards