Check Whether Bracket Pairs Are Correctly Nested
Stacks & QueuesAuto-graded · 25 test casesLast updated
Decide whether a string of round, square and curly brackets is well formed, which tests the use of a stack for last-in-first-out matching.
Check Whether Bracket Pairs Are Correctly Nested
You are given a string text made up only of bracket characters: (, ), [, ], { and }. Decide whether the brackets are well formed.
A string is well formed when all of the following hold:
- Every opening bracket is closed by a bracket of the same kind (
(with),[with],{with}). - Brackets are closed in the reverse of the order they were opened, so the most recently opened bracket that is still open must be the next one to close.
- No closing bracket appears without a matching opening bracket before it.
- No opening bracket is left unclosed at the end of the string.
The empty string is considered well formed.
Return True if text is well formed, otherwise False.
Constraints
0 <= len(text) <= 10^5textcontains only the characters(,),[,],{and}.
Examples
Example 1
Input: is_well_formed('()[]{}')
Output: True
Example 2
Input: is_well_formed('([)]')
Output: False
Example 3
Input: is_well_formed('{[]}')
Output: True
Hints
Hint 1
Think about which opening bracket a closing bracket is allowed to pair with. It must be the most recently opened one that is still unclosed.
Hint 2
Keep a stack of opening brackets as you scan from left to right. Push on every opener; on every closer, compare it with the top of the stack.
Hint 3
Handle two failure cases while scanning (closer with an empty stack, closer of the wrong kind) and one at the end (openers still left on the stack).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The rule "the last bracket opened must be the first one closed" is a last-in-first-out rule, so a stack fits naturally.
Scan the string from left to right:
- Opening bracket: push it onto the stack. It is now the innermost bracket still waiting to be closed.
- Closing bracket: it has to close the innermost open bracket, which is the top of the stack. Return
Falseif the stack is empty (nothing to close) or if the popped opener is not the matching kind. - End of the string: every opener must have been closed, so the stack must be empty. Return whether it is.
A dictionary from each closer to its opener makes the kind check a single lookup.
Why it is correct
At any moment the stack holds exactly the openers seen so far that have not been closed, with the most recent on top. A closer is legal only if it matches that most recent opener, which is what we test. An empty stack on a closer catches strings like "]", a mismatch catches "(]" and "([)]", and a non-empty stack at the end catches "(()". If none of these failures occur, every closer was paired with its innermost opener and nothing remains open, which is exactly the definition of a well-formed string. The empty string never enters the loop and leaves an empty stack, so it returns True.
A plain counter per bracket type is not enough: "([)]" has balanced counts but is invalid.
Complexity
- Time: O(n), each character is handled once with O(1) work.
- Space: O(n) in the worst case, for example a string containing only openers.
Reference solution
def is_well_formed(text: str) -> bool:
closer_to_opener = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in text:
if ch in '([{':
stack.append(ch)
elif not stack or stack.pop() != closer_to_opener[ch]:
return False
return not stack