KatInterview

Balanced Delimiters Checker

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

Last 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^5
  • text contains 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.