Valid Parentheses
Valid Parentheses is an easy coding interview question. You’re given a string s that holds only the characters (, ), [, ], { and }. Return true if its brackets are balanced, and false otherwise. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.
Updated · By InterviewMind
Free in your browser, no account.
The problem
Coding · Easy
You’re given a string s that holds only the characters (, ), [, ], { and }. Return true if its brackets are balanced, and false otherwise.
Balanced means every opening bracket is closed by one of the same kind, brackets close in the reverse of the order they opened, and no closing bracket shows up without an open one to match.
Example 1
s = "()[]{}"OutputtrueExample 2
s = "([{}])"OutputtrueEach bracket closes after everything opened inside it.
Example 3
s = "(]"OutputfalseA round bracket can’t be closed by a square one.
Example 4
s = "([)]"OutputfalseThe square bracket opened last, so it has to close before the round one.
Constraints
- 1 ≤ s.length ≤ 10⁴
- s holds only the characters ()[]{}
Hints
Open one at a time, and try the question again after each.
Hint 1
The bracket that has to close next is always the one opened most recently. Whatever you keep the open brackets in should hand that one back first.
Hint 2
Push each opening bracket onto a stack. On a closing bracket, pop the top and check it’s the matching kind; a small map from each closer to its opener keeps that check short.
Hint 3
Two failures are easy to miss: a closing bracket when the stack is already empty, and opening brackets still left on the stack when the string ends.
Practice it out loud
In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.
Practice this questionMore coding questions
- Merge Intervals · Medium
- LRU Cache · Medium
- Two Sum · Easy
- Longest Substring Without Repeating Characters · Medium
- Top K Frequent Elements · Medium
- Number of Islands · Medium
More on these rounds: Coding interview practice.