Validate Balanced Round, Square and Curly Brackets
Stacks & QueuesAuto-graded · 28 test casesLast updated
Decide whether a string of three bracket kinds is balanced, testing last-in-first-out matching with a stack and handling crossings and leftover or stray brackets.
Balanced Brackets
You are given a string text that contains only the six characters (, ), [, ], { and }. Determine whether the brackets are balanced, that is, whether they form a valid, properly nested structure.
Matching rules
- Each opening bracket has exactly one matching closing type:
(with),[with], and{with}. - When a closing bracket appears, it must close the opening bracket that was opened most recently and has not yet been closed. That bracket must be of the matching type.
- If a closing bracket appears when no bracket is currently open, the string is not balanced.
- If any opening bracket is still unclosed once the whole string has been read, the string is not balanced.
- Pairs may follow one another (
()[]) or contain one another ({[()]}), but they must not overlap. In([)], the)appears while[is the innermost open bracket, so the string is not balanced.
Return True if the string is balanced, otherwise False.
Constraints
1 <= len(text) <= 10^4- Every character of
textis one of(,),[,],{,}.
Examples
Example 1
Input: is_balanced_brackets('{[()]}()')
Output: True
Example 2
Input: is_balanced_brackets('([)]')
Output: False
Example 3
Input: is_balanced_brackets('[]{')
Output: False
Hints
Hint 1
Closing brackets must match the most recently opened bracket that is still open. Which data structure gives you last-in, first-out access?
Hint 2
Counting each bracket type separately is not enough, because it accepts crossing pairs like "([)]". You need to remember the order in which brackets were opened.
Hint 3
There are two ways to fail: a closing bracket arrives when nothing is open or the top of the stack is the wrong type, and the stack is not empty after the last character.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The rule that a closing bracket must close the most recently opened, still-open bracket 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 open bracket.
- Closing bracket: if the stack is empty, nothing is open, so return
False. Otherwise pop the top of the stack and compare it with the opener that this closer requires. If they differ, returnFalse. - End of string: the string is balanced only if the stack is empty. Anything left over was opened but never closed.
A small dictionary from each closer to its opener serves two purposes: membership tells us whether a character is a closer, and the value gives the required opener.
Why it is correct
At every step the stack holds exactly the currently open brackets, ordered from oldest (bottom) to newest (top). Pushing adds a newly opened bracket on top. A successful pop removes precisely the bracket the closer closes, exposing the previous innermost one.
With this invariant, each rule maps to one check:
- A closer must match the most recent open bracket's type: compare the popped top with the required opener.
- A closer with nothing open is invalid: check for an empty stack before popping.
- Every opener must be closed: require an empty stack at the end.
Returning early on the first failure is safe, because no later character can repair a mismatched or stray closer. Crossing pairs such as ([)] are rejected since only the innermost open bracket is ever available to match.
Complexity
- Time: O(n), each character is handled once with O(1) work.
- Space: O(n) in the worst case, for example a string made of only openers.
Reference solution
def is_balanced_brackets(text: str) -> bool:
# Map each closing bracket to the opener it must match.
partner = {")": "(", "]": "[", "}": "{"}
open_stack = []
for ch in text:
if ch in partner:
# Closer: something must be open and it must be the right type.
if not open_stack or open_stack.pop() != partner[ch]:
return False
else:
# Opener: becomes the most recently opened bracket.
open_stack.append(ch)
# Every opener must have been closed.
return not open_stack