Valid Parentheses
On this page
Problem statement
Given a string containing only the characters ( ) [ ] { }, decide whether it is valid: every opening bracket is closed by a bracket of the same type, and brackets close in the correct order. An empty string is valid.
One of the most common warm-up questions. It's short, but it checks whether you reach for the right structure (a stack) and handle the two ways it can fail: a mismatch in the middle, and leftovers at the end. Original problem: LeetCode 20.
Example

Input: "([{}])"
Output: true
Input: "([)]"
Output: false # ) arrives while [ is still open
Constraints (assumed)
- 0 ≤ length ≤ 10,000.
- Only the six bracket characters.
What this question tests
- Recognizing last opened, first closed and choosing a stack.
- Handling both failure points: mismatch during the scan and leftovers at the end.
- Clean code with a small lookup table instead of a chain of ifs.
Questions to ask first
- Only brackets, or other characters too? (Here: only brackets. If other characters appear, skip them.)
- Is the empty string valid? (Here: yes.)
- Only one bracket type? If so, a counter is enough; with several types you need order.
- Return true/false, or the position of the first error? (Here: true/false.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.