⌘K
Flycodx

Valid Parentheses

Valid Parentheses

EasyStacks57% accepted

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

YES
  • •1 ≤ len(s) ≤ 10^4
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3