Valid Parentheses
Real-world version: Template Grouping CheckThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def is_balanced(code: str) -> bool:public boolean isBalanced(String code)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Remove All Adjacent Duplicates In StringReal-world version: Settle the Loom TapeEasy
- Remove Outermost ParenthesesReal-world version: Strip Root Frame MarkersEasy
- Backspace String CompareReal-world version: Strike Marks On Two TapesEasy
- Maximum Nesting Depth of the ParenthesesReal-world version: Deepest Bracket LayerEasy