KatInterview

Balanced Delimiter Validation with a Stack

Stacks & QueuesAuto-graded · 23 test cases
EasyAuto-gradedStacks & Queuesstackstringsparsing

Last updated

Decide whether a bracket-only string is properly nested and matched, using a LIFO stack of pending openers.

You are given a string brackets containing only the six delimiter characters (, ), [, ], {, }.

Decide whether the string is well formed. A string is well formed exactly when all three conditions hold:

  1. Each opening delimiter is eventually closed by a delimiter of the same kind.
  2. Delimiters close in properly nested order — the most recently opened delimiter must be the next one closed.
  3. A closing delimiter never appears without a matching opener of the same kind still waiting to be closed.

Return True if the string is well formed, otherwise return False.

Constraints

  • 1 <= len(brackets) <= 10^4
  • brackets consists only of the characters (, ), [, ], {, }.

Examples

Example 1

Input: is_well_formed('()[]{}')

Output: True

Example 2

Input: is_well_formed('([)]')

Output: False

Example 3

Input: is_well_formed('{[]}')

Output: True

Hints

Hint 1

Nesting is last-in-first-out, so track pending openers in a stack.

Hint 2

When a closer arrives, the thing it must match is exactly the most recent unmatched opener.

Hint 3

Three failure signals: a closer with an empty stack, a closer that disagrees with the stack top, and openers left over at the end.