CodeArchon

easyStackAmazonGoogleMicrosoft

Bracket Balance Audit

A linter inspects a punctuation string containing `()`, `[]`, and `{}`. Every opener must be closed in the correct order.

Given a string of `()[]{}`, decide whether every open bracket is closed by the matching type in the right order.

Choose approach

Input
(
)
[
]
{
}
top
1/8
Narrationstep 1 of 8

Walk the string. Push every opener; on a closer, the stack top must match or we reject.

1def bracket_balance_audit(s: str) -> bool:
2 pair = {')': '(', ']': '[', '}': '{'}
3 stack: list[str] = []
4 for c in s:
5 if c in '([{':
6 stack.append(c)
7 elif not stack or stack.pop() != pair[c]:
8 return False
9 return not stack
Variables
i=0
stack.size=0

How to think about it

  1. Brackets must match last-in-first-out — a stack is the natural fit.
  2. Push every opener.
  3. On a closer, the top of the stack must be the matching opener.
  4. If the stack is empty or the top mismatches → reject.
  5. After scanning, the stack must be empty.

Edge cases to catch in interview

  • Empty string → vacuously balanced.
  • Only closers → immediate reject.
  • Only openers → stack non-empty at end → reject.

Examples

Example 1true
{"text":"()[]{}"}
Example 2false
{"text":"(]"}
Example 3true
{"text":"([{}])"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed