You are given a string that contains only the six bracket characters (, ), [, ], {, and }.
The string is balanced when every opening bracket has a matching closing bracket of the same type, the pairs are properly nested, and no closing bracket appears without a matching open bracket before it. An empty string is considered balanced.
Print whether the given string is balanced.
Line 1: an integer n, the length of the string.
Line 2: the string of exactly n bracket characters. When n is 0 this line is present but empty.
Print YES if the string is balanced, otherwise print NO.
(, ), [, ], {, }.Example 1
Input
6
([]{})Expected
YES
Explanation
Reading left to right, every closer matches the most recent opener of the same type and the stack ends empty, so the string is balanced.
Example 2
Input
4 ([)]
Expected
NO
Explanation
When `)` is read the most recent unmatched opener is `[`, not `(`, so the brackets are interleaved rather than nested and the answer is NO.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →