#K84697. Balanced Parentheses Checker
Balanced Parentheses Checker
Balanced Parentheses Checker
You are given an expression consisting solely of the characters (
and )
. Your task is to determine whether the expression is balanced or not. An expression is considered balanced if and only if:
- For every opening parenthesis
(
there exists a corresponding closing parenthesis)
. - At no point in the expression does the number of closing parentheses exceed the number of opening parentheses.
In mathematical terms, if we denote the expression by \(S\), then \(S\) is balanced if for every prefix \(S'\) of \(S\),
\[
\#( (S') \geq \#) (S')
\]
and the total number of (
equals the total number of )
in \(S\).
You will be given several expressions and you need to output YES
if an expression is balanced, or NO
otherwise.
inputFormat
The input is read from stdin and has the following format:
<integer n> <expression_1> <expression_2> ... <expression_n>
Here, n
(\(1 \leq n \leq 10^5\)) is the number of expressions, followed by n
lines, each containing an expression that consists of characters (
and )
. Note that an expression might be an empty string, which is considered balanced.
outputFormat
For each expression, output a single line to stdout containing either YES
if the expression is balanced or NO
if it is not.
4
()
((()))
(()))
((()()
YES
YES
NO
NO
</p>