Suppose we have a string S with n characters. S contains lowercase English letters and ')' characters. The string is bad, if the number of characters ')' at the end is strictly greater than the number of remaining characters. We have to check whether S is bad or not.
So, if the input is like S = "fega))))))", then the output will be True, because this is bad as there are 4 letters and 6 ')'s.
Steps
To solve this, we will follow these steps −
ans := 0 n := size of S i := n - 1 while (i >= 0 and S[i] is same as ')'), do: (decrease i by 1) z := n - 1 - i ans := 2 * z - n if ans > 0, then: return true Otherwise return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
bool solve(string S) {
int ans = 0;
int n = S.size();
int i = n - 1;
while (i >= 0 && S[i] == ')')
i--;
int z = n - 1 - i;
ans = 2 * z - n;
if (ans > 0)
return true;
else
return false;
}
int main() {
string S = "fega))))))";
cout << solve(S) << endl;
}Input
"fega))))))"
Output
1