Official algorithmic problem description and constraints.
Yousef has given you a sequence π
of length π
consisting only of characters '(
' and ')
'. You are allowed to perform the following operation at most once:
Yousef wants you to determine whether it is possible to obtain a regular bracket sequence
β
after performing the operation at most once.
β
A substring is a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3
and ends in position 6
), but "aa" or "d" aren't substrings of this string. So the substring of the string π
from position π
to position π
is π [π,π]=π
π
π
π+1
β¦π
π
.
β
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting the characters 1
and +
between the original characters of the sequence. For example:
Input
The first line contains an integer π‘
(1β€π‘β€10
4
) β the number of test cases. The descriptions of the test cases follow.
The first line of each test case contains a single integer π
(1β€πβ€2β 10
5
) β the length of the string π
.
The second line of each test case contains a sequence π
of length π
consisting only of characters '(
' and ')
'.
It is guaranteed that the sum of π
over all test cases does not exceed 2β 10
5
.
Output
For each test case, output "YES" if the sequence can be made regular, and "NO" otherwise.
You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.
Example
Input
Copy
6 2 () 2 )( 3 ((( 6 ())(() 4 (()( 5 )()()
Output
Copy
YES YES NO YES NO NO
Note
In the first test case, the string π
is already a regular bracket sequence, therefore the answer is "YES".
In the second test case, we can remove the substring π [2,2]=(
and reinsert it at the beginning of the string, making π =()
, therefore the answer is "YES".
In the third test case, there is no way to do the operation and get a regular bracket sequence, so the answer is "NO".
In the fourth test case, we can choose the substring π [3,4]=)(
, remove it, then reinsert the characters as follows:
())(()β()()β(()())
Therefore we have made a regular bracket sequence, and the answer is "YES".
Detailed video explanations, mathematical intuition, and clean C++ implementation code.