← Back to DSA mapEasy
Stack
Valid Parentheses
Are the brackets in a string properly opened and closed?
Problem
Given a string s containing only the characters ( ) { } [ ], determine whether the string is valid.
- Open brackets must be closed by the same type.
- Open brackets must be closed in the correct order.
- Every closing bracket has a matching opening bracket.
Examples
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
( is closed by ].
Input: s = "([)]"
Output: false
The order is wrong.
Input: s = "{[]}"
Output: true
Approach
Time O(n)Space O(n)
- Keep a stack of open brackets and a map from each opener to its closer.
- Push every opening bracket.
- For a closing bracket, pop the top. If the stack was empty or the popped opener does not match, the string is invalid.
- At the end the stack must be empty - leftovers are openers that were never closed.
Common mistakes
- Returning true at the end without checking the stack is empty accepts "((".
- Counting brackets per type misses order: "([)]" has balanced counts but is invalid.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
STACK
Solution · JS
String · i=— ch=—
(0
)1
STACK[ ]
matching info appears here
Index
—
Char
—
Stack
0
Need
—
Valid
—
0 / 0
1×
Execution log
steps appear here…
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
Edit and run it here
JavaScript solution
Loading...
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
All courses
24 courses in 5 subjects
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned
Frontend
Fundamentals
On this page
0 sections