KatInterview

Validate Balanced Round, Square and Curly Brackets

Stacks & QueuesAuto-graded · 28 test cases
MediumAuto-gradedStacks & Queuesstackstringsparsing

Last updated

Decide whether a string of three bracket kinds is balanced, testing last-in-first-out matching with a stack and handling crossings and leftover or stray brackets.

Balanced Brackets

You are given a string text that contains only the six characters (, ), [, ], { and }. Determine whether the brackets are balanced, that is, whether they form a valid, properly nested structure.

Matching rules

  • Each opening bracket has exactly one matching closing type: ( with ), [ with ], and { with }.
  • When a closing bracket appears, it must close the opening bracket that was opened most recently and has not yet been closed. That bracket must be of the matching type.
  • If a closing bracket appears when no bracket is currently open, the string is not balanced.
  • If any opening bracket is still unclosed once the whole string has been read, the string is not balanced.
  • Pairs may follow one another (()[]) or contain one another ({[()]}), but they must not overlap. In ([)], the ) appears while [ is the innermost open bracket, so the string is not balanced.

Return True if the string is balanced, otherwise False.

Constraints

  • 1 <= len(text) <= 10^4
  • Every character of text is one of (, ), [, ], {, }.

Examples

Example 1

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

Output: True

Example 2

Input: is_balanced_brackets('([)]')

Output: False

Example 3

Input: is_balanced_brackets('[]{')

Output: False

Hints

Hint 1

Closing brackets must match the most recently opened bracket that is still open. Which data structure gives you last-in, first-out access?

Hint 2

Counting each bracket type separately is not enough, because it accepts crossing pairs like "([)]". You need to remember the order in which brackets were opened.

Hint 3

There are two ways to fail: a closing bracket arrives when nothing is open or the top of the stack is the wrong type, and the stack is not empty after the last character.