Balanced Delimiters Checker
Stacks & QueuesAuto-graded · 23 test casesLast updated
Decide whether a string made only of round, square and curly brackets is correctly paired and nested, which tests stack-based matching and edge-case handling.
You are given a string text made up exclusively of these six characters: (, ), [, ], { and }.
Decide whether the delimiters in text are balanced. The string is balanced when all of the following hold:
- Each opening delimiter is eventually closed by a delimiter of the same kind (
(with),[with],{with}). - Delimiters close in the right order: whichever one was opened most recently and is still unclosed must be the next one to close.
- A closing delimiter never appears when there is no earlier, still-unclosed opening delimiter for it to match.
Return True if text is balanced, otherwise return False. The empty string counts as balanced.
Constraints
0 <= len(text) <= 10^5textcontains only the characters(,),[,],{,}.- The function returns a boolean.
Examples
Example 1
Input: is_balanced('()[]{}')
Output: True
Example 2
Input: is_balanced('([)]')
Output: False
Example 3
Input: is_balanced('{[]}')
Output: True
Hints
Hint 1
Think about which opening bracket a closing bracket is allowed to pair with. It is always the most recent one that is still unclosed.
Hint 2
A last-in, first-out structure fits this naturally. Push each opener, and on each closer compare it against the top of that structure.
Hint 3
Handle two failure cases separately: a closer arriving when nothing is open, and openers left over after the whole string has been read.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Brackets nest, so the most recently opened bracket must be the first one closed. That is last-in, first-out behavior, which a stack models directly.
Scan the string from left to right:
- On an opening bracket, push it onto the stack.
- On a closing bracket:
- If the stack is empty, there is nothing for it to close, so return
False. - Otherwise pop the top. If it is not the opener matching this closer, return
False.
- If the stack is empty, there is nothing for it to close, so return
- After the scan, return
Trueonly if the stack is empty. Any opener left over was never closed.
A dictionary from each closer to its opener makes the match check a single comparison.
Why it is correct
After processing any prefix, the stack holds exactly the unclosed openers of that prefix, in the order they were opened. In a valid string, a closer can only close the innermost open bracket, which is the top of the stack, so checking only the top is both necessary and sufficient. A closer on an empty stack has no partner, and a non-empty stack at the end means some opener was never closed. If none of these failures occur, every opener was paired with a same-type closer in properly nested order.
Counting bracket types alone is not enough: "([)]" has one of each type but is invalid because the nesting crosses.
Edge cases
- Empty string: the loop never runs and the stack is empty, so the result is
True. - A closer first, such as
")": the empty-stack check comes before the pop, so no error occurs and the result isFalse. - Leftover openers, such as
"((": the stack is non-empty at the end, so the result isFalse. - Type mismatch, such as
"(]": the popped opener does not match, so the result isFalse.
Complexity
- Time: O(n), since each character is handled once with O(1) work.
- Space: O(n) in the worst case, for example a string of only openers.
Reference solution
def is_balanced(text: str) -> bool:
# Map each closing bracket to the opening bracket it must match.
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in text:
if ch in '([{':
stack.append(ch)
elif not stack or stack.pop() != pairs[ch]:
return False
return not stack