A string consisting only of parentheses \verb+(+ and \verb+)+ is called a parentheses string. The balanced parentheses strings are defined recursively as follows:
- An empty string is a balanced parentheses string.
- If s is a balanced parentheses string, then \verb+(+s\verb+)+ is also a balanced parentheses string.
- If s and t are balanced parentheses strings, then st (concatenation of s and t) is also a balanced parentheses string.
For a parentheses string, an operation on this string is defined as follows:
- Choose any substring of this string which is balanced.
- Remove this substring and concatenate the remaining parts.
Given a parentheses string S, find the minimum length of the string one can get by applying the above operation any number of times. Also find the minimum number of operations required to achieve this minimum length.
The first observation that we can make is that on removing a balanced parenthesis from the string, it won’t affect other balanced parenthesis in the remaining string. So what we can do is remove all the balanced parenthesis from the string and then on the final string left, we can calculate the number of operations by counting the number of missing segments in it.
In order to implement it we can replace the string by a vector v, where
Now we can take another vector, say res and loop through the vector v and for any index i, which has a closing bracket, i.e v[i] < 0, if we can find a corresponding opening bracket at index j, that makes string s[j...i], balanced, i.e we find res not empty and last element of res to be positive, we simply remove the last element of res, implying that substring s[j....i] is removed, otherwise we simply add v[i] to res
Thus in the end res would contain the indexes of the final string after removing all the possible balanced parenthesis from the original string.
The size of res would be the first part of the answer, i.e the length of the final string. As for the number of operations, we have the indexes of the characters of the final string, so we can just count the number of missing segments to get the second part of the answer.
O(N), for each test case.