KatInterview

Check Whether Bracket Pairs Are Correctly Nested

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

Last updated

Decide whether a string of round, square and curly brackets is well formed, which tests the use of a stack for last-in-first-out matching.

Check Whether Bracket Pairs Are Correctly Nested

You are given a string text made up only of bracket characters: (, ), [, ], { and }. Decide whether the brackets are well formed.

A string is well formed when all of the following hold:

  1. Every opening bracket is closed by a bracket of the same kind (( with ), [ with ], { with }).
  2. Brackets are closed in the reverse of the order they were opened, so the most recently opened bracket that is still open must be the next one to close.
  3. No closing bracket appears without a matching opening bracket before it.
  4. No opening bracket is left unclosed at the end of the string.

The empty string is considered well formed.

Return True if text is well formed, otherwise False.

Constraints

  • 0 <= len(text) <= 10^5
  • text contains only the characters (, ), [, ], { and }.

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

Think about which opening bracket a closing bracket is allowed to pair with. It must be the most recently opened one that is still unclosed.

Hint 2

Keep a stack of opening brackets as you scan from left to right. Push on every opener; on every closer, compare it with the top of the stack.

Hint 3

Handle two failure cases while scanning (closer with an empty stack, closer of the wrong kind) and one at the end (openers still left on the stack).