Nested Delimiter Checker for Config Expressions
Stacks & QueuesAuto-graded · 26 test casesLast updated
Checks whether a string of mixed parentheses, braces, and square brackets is properly nested, testing stack-based matching and early rejection in linear time.
Nested Delimiter Checker for Config Expressions
Configuration validators and log processors often need to confirm that a structured snippet, such as a query, a JSON fragment, or a firewall rule, has delimiters that open and close correctly.
Given a string expr made up only of the six delimiter characters (, ), {, }, [, and ], return True if the delimiters are properly nested and False otherwise.
A string is properly nested when all of the following hold:
- Every opening delimiter is closed by a delimiter of the same kind.
- Delimiters close in the reverse of the order they were opened, so pairs never cross.
- Every closing delimiter has an earlier unmatched opening delimiter to pair with.
An empty string has nothing unmatched, so it counts as properly nested.
Function Signature
def check_delimiters(expr: str) -> bool:
pass
Input and Output Format
- Input: a single string
exprcontaining only the characters(,),{,},[, and]. - Output:
Trueif the delimiters are properly nested, otherwiseFalse.
Constraints
0 <= len(expr) <= 10^5exprcontains only the characters(,),{,},[, and].- The solution must run in
O(n)time and useO(n)auxiliary space.
Examples
Example 1
Input: check_delimiters('{[()]}')
Output: True
Example 2
Input: check_delimiters('([)]')
Output: False
Example 3
Input: check_delimiters(']')
Output: False
Hints
Hint 1
Think about which opening delimiter must be closed first when a closing one appears. The most recently opened unmatched delimiter is the one that has to close next, which points to a stack.
Hint 2
When a closing delimiter arrives, check two failure cases before comparing: the stack might be empty, or the top might be a delimiter of a different kind. A lookup table from each closer to its expected opener keeps this check short.
Hint 3
A stack that is empty at the end is required for success. Any leftover opener means something was never closed, so do not forget the final check.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the string from left to right and keep a stack of openers that have not been closed yet.
- When you see an opener
(,{, or[, push it. - When you see a closer
),}, or], it must match the most recent unmatched opener, which is the top of the stack. If the stack is empty, or the top is the wrong kind, the string is invalid. - After the scan, the string is valid only if the stack is empty.
A small dictionary maps each closer to its required opener, so each check is a single lookup.
As a shortcut, any string with odd length has an unpaired delimiter and can be rejected before scanning.
Why It Is Correct
After processing any prefix, the stack holds exactly the openers in that prefix that are still unmatched, with the most recent one on top. A closer can only be valid if it pairs with the most recent unmatched opener. If it paired with an older one, the newer opener would be left crossing the pair, as in ([)]. So checking the top of the stack enforces both the matching-kind rule and the nesting-order rule. An empty stack when a closer arrives means that closer has no partner. A non-empty stack at the end means some opener was never closed. These are exactly the conditions for proper nesting.
Complexity
- Time:
O(n). Each character is handled once, and each push, pop, and dictionary lookup takes constant time. - Space:
O(n)in the worst case, for a fully nested string such as"((((...))))". More precisely, the space is proportional to the maximum nesting depth.
Edge Cases
- Empty string: the loop does nothing, the stack is empty, and the result is
True. - Odd length, such as
"((("or"([]": rejected immediately. - Closer first, such as
")(": the stack is empty when the closer arrives, so the result isFalse. - Leftover openers, such as
"((": the scan finishes, but the stack is not empty, so the result isFalse. - Right counts in the wrong order, such as
"([)]": the top of the stack is[when)arrives, so the result isFalse.
Reference Solution
def check_delimiters(expr: str) -> bool:
"""
Return True if the bracket characters in expr are properly nested.
Only the characters ( ) { } [ ] appear in expr. Each opener must be
closed by the matching closer, and pairs must not cross. The empty
string returns True.
"""
# An odd-length string cannot be made of complete pairs.
if len(expr) % 2:
return False
# Each closer maps to the opener it must pair with.
partner = {')': '(', '}': '{', ']': '['}
open_stack = []
for ch in expr:
if ch in '({[':
open_stack.append(ch)
elif not open_stack or open_stack.pop() != partner[ch]:
# Either nothing is open, or the most recent opener is the wrong kind.
return False
# Every opener must have been closed.
return not open_stack