All problems
0003EasyStringStack

Template Grouping Check

Tracked in this browser only
Write code

Trains the technique from

LeetCode 20Valid Parentheses

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A template compiler scans a source file, discards every character that is not a grouping mark, and keeps what remains in order as the string code. So code is built only from round marks ( and ), square marks [ and ], and curly marks { and }. The compiler only runs this check on files that contained at least one grouping mark.

The compiler calls the grouping sound when the marks can be paired off so that all of the following hold:

  • Every mark belongs to exactly one pair.
  • In each pair, an opener comes first and a closer of the same shape comes later.
  • No two pairs cross: for any two pairs, one is either entirely inside the other or entirely outside it.

Return true when the grouping in code is sound, and false when no such pairing exists.

Examples

Example 1

Input
code = "([]{})"
Output
true

The square pair and the curly pair both sit entirely inside the round pair, so nothing crosses and every mark is used exactly once.

Example 2

Input
code = "{(})"
Output
false

Pairing the round marks and the curly marks here forces the two pairs to cross, and no other pairing is available.

Example 3

Input
code = "[[]"
Output
false

There are three marks, an odd count, so at least one cannot belong to a pair.

Example 4

Input
code = "]"
Output
false

A single closer has no opener before it to pair with.

Constraints

  • 1 <= code.length <= 10^4
  • `code` contains only the six characters `(`, `)`, `[`, `]`, `{`, `}`

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def is_balanced(code: str) -> bool:
Java
public boolean isBalanced(String code)
September 7
Apply