The following question was asked to my friend in an interview : given a string consisting only of '(' and ')'. find total number of substrings with balanced parenthesis Note: the input string is already balanced.
The only solution i can think of this problem is brute force which takes n^3 time. Is there a faster solution possible.If there is then i would also like to know the build up to that approach.
Consider open parenthesis as 1 and closing parenthesis as -1, so necessary conditions for substring to be balanced are:
OK, now compute L[i] = total sum of elements from index 1 to i. So for each left index l that is an open parenthesis (value 1), find with binary search maximum possible right index r such that there isn't an index i between l and r with L[i] < L[l] - 1. This ensures condition 2. You can do this step with a segment tree or a sparse table. Now to satisfy condition 1, find all indexes i between l and r such that L[i] = L[l] - 1. You can do this one with binary search too, for example by storing positions for given sum s in a vector Pos[s].
Overall complexity of the algorithm is O(NlogN) if you precompute values with a sparse table or O(Nlog2N) if you use segment tree during the binary search.
nice
Thanks for explaination
I am so sorry for necroposting, but I can't help not posting an alternate cleaner solution which is inspired from the Editorial for 1976D - Invertible Bracket Sequences.
Please go through this problem and it's editorial. You may also go through my submission for the same problem, IIRC I added a comment which may help you if you face difficulty at any point.
This code prints the number of balanced substrings of a bracket sequence which itself may or may not be balanced.
I saw the editorial and I think it has the same solution but in the editorial it was not clear for me why the condition p[i] >= p[l-1] should hold
Can anybody tell If my approach is right or not ?
C++ code
string s;
cin>>s;
int ans = 0;
vector v;
for(int i =0;i<s.length();i++){
if(s[i]=='('){
}
else{
}
}
int n =v.size();
ans += n*(n+1)/2;
v.clear();
cout<<ans<<endl;
Time complexity will be O(N)
")()(" gives 6 seems wrong. I had to add a few v.empty() checks to prevent the code from top/pop on an empty stack.
You are just 4 years late.
Yeah, just stumbled on this problem. Still wonder if there is a valid O(n) solution.
if the length of string is not large you can use a simple O(n^2) solution .
can you also find an efficient way to say if we reverse any substring will it be valid , given the input is not necessarily initially valid
if you would have send this 8 years ago then maybe...
We can do this , lets define the level of any "()" to be the number of opening brackets under which it appears so just count number of "()" and for every "()" also add in the answer the number of balanced substrings appearing in that level .
This is an incorrect approach. Correct answer for the string $$$(()())(()())$$$ is $$$9$$$ while your code gives output $$$13$$$.