Easy C++ solution without using stacks

int Solution::solve(string A) 
{
    int open=0,close=0;
    for(int i=0;i<A.length();i++)
    {
        if(A[i]=='(')
        {
            open++;
        }
        else
        {
            close++;
        }
        if(close>open)
        {
            return 0;
        }
    }
    return open==close;
}

It’ll fail for cases where close=open but the string isn’t balanced.
such as this “)))(((”

Should be changed to this:

int Solution::solve(string A) {
int open=0, close=0;
for(int i=0; i<A.length(); i++){
if(A[i]==’(’){
open++;
}
else{
if(open){
open–;
}
else{
close++;
}
}
}

return (open+close>0)?0:1;

}

Click here to start solving coding interview questions