Valid Parentheses
How the interviewer asks it
“Given a string containing only the characters ( ) [ ] { }, decide whether every bracket is closed by the same type of bracket in the right order.”
([]){}true
In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.
Typed drills are free and unlimited: the AI scores your answer against the outline below.
What the interviewer is looking for
- You recognise last-opened, first-closed as a stack.
- You cover all three failure cases: wrong type, a closer with nothing open, and openers left over at the end.
- A tidy mapping from closer to opener instead of a chain of if statements.
- Quick, confident testing on the empty string and on "(]".
How to structure your answer
- 01
Clarify
Ask whether the empty string is valid (usually yes) and whether other characters can appear.
- 02
Stack
Push every opener. For a closer, the stack must be non-empty and its top must be the matching opener; pop it.
- 03
Finish
The string is valid only if the stack is empty at the end.
- 04
Test
"()[]{}" is valid, "([)]" is not, "((" is not, ")" is not.
- 05
Complexity
O(n) time and O(n) space in the worst case.
Best answers from candidates
No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.
Answers are shared by candidates, without names, after a privacy check. Add yours
Common mistakes
- Popping from an empty stack and crashing on a string like ")(".
- Returning true without checking the stack is empty at the end.
- Counting brackets of each type, which passes "([)]" wrongly.
Follow-up questions to expect
- Return the minimum number of brackets to add to make it valid.
- Find the length of the longest valid substring.
- Can you do it in O(1) space if there is only one type of bracket?
Now answer it out loud
Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.
More coding interview questions
Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.