Well-Formed Bracket Sequence Checker
Stacks & QueuesAuto-graded · 27 test casesLast updated
Decide whether a string of three kinds of brackets is correctly nested, using a stack to enforce that the most recently opened bracket is closed first.
Well-Formed Bracket Sequence
You are given a string text made up only of the six characters (, ), [, ], { and }. Decide whether the brackets in it form a well-formed sequence.
A sequence is well-formed when all of the following hold:
- Each closing bracket ends an opening bracket of the same kind (
)with(,]with[,}with{). - Brackets are closed in the reverse order from which they were opened, so pairs may be nested but never cross each other.
- No closing bracket appears without a matching opening bracket before it, and no opening bracket is left unclosed at the end.
Return True if text is well-formed, otherwise return False.
Constraints
1 <= len(text) <= 10^4textcontains only the characters()[]{}- Return a boolean (
TrueorFalse)
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
The bracket that was opened most recently must be the first one to be closed. Which data structure gives you that last-in, first-out behavior?
Hint 2
When you see a closing bracket, compare it with the most recent unmatched opening bracket. If none exists, or the kinds differ, the string is invalid. Be careful not to look at an empty structure.
Hint 3
Matching every closer is not enough. After scanning the whole string, make sure no opening brackets remain unmatched. Also note that counting each bracket type separately would wrongly accept a crossing case like `([)]`.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Brackets must be closed in the opposite order to the one in which they were opened, which is last-in, first-out behavior. A stack models this directly.
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 must close the innermost open bracket, which is the top of the stack. If the stack is empty, or the top is a different kind of bracket, return
False. Otherwise pop the top, since that pair is resolved. - End of string: the sequence is well-formed only if the stack is empty. Any remaining entries are openers that were never closed.
A dictionary mapping each closer to its opener makes the type check a single comparison.
Why it is correct
After processing any prefix, the stack holds exactly the unmatched opening brackets of that prefix, in the order they were opened.
- Pushing an opener preserves this.
- A closer can only legitimately pair with the most recent unmatched opener. Pairing with an earlier one would make the pairs cross, as in
([)]. So checking only the top of the stack is both necessary and sufficient. - A closer arriving on an empty stack has no partner, so the string is invalid.
- Leftover openers at the end were never closed, so the string is invalid.
If the scan finishes with no early failure and an empty stack, every bracket was matched with the right kind in the right order.
Complexity
- Time: O(n), as each character is handled once with O(1) work.
- Space: O(n) in the worst case, for example when the string consists only of 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[-1] != closer_to_opener.get(ch):
return False
else:
stack.pop()
return not stack