KatInterview

Nested Delimiter Checker for Config Expressions

Stacks & QueuesAuto-graded · 26 test cases
EasyAuto-gradedStacks & Queuesstackparsingstring

Last 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:

  1. Every opening delimiter is closed by a delimiter of the same kind.
  2. Delimiters close in the reverse of the order they were opened, so pairs never cross.
  3. 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 expr containing only the characters (, ), {, }, [, and ].
  • Output: True if the delimiters are properly nested, otherwise False.

Constraints

  • 0 <= len(expr) <= 10^5
  • expr contains only the characters (, ), {, }, [, and ].
  • The solution must run in O(n) time and use O(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.