# https://www.codechef.com/COLE2020/problems/CLBRKT

``````#include <bits/stdc++.h>
using namespace std;

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long t;
cin>>t;
for(long long i=0;i<t;i++)
{
string s;
cin>>s;
long long  n=s.length();
long long q;
cin>>q;
vector <long long> tim(n+1,0);

stack < pair <char ,long long > > st;
st.push({'a',0});
for(long long j=0;j<n;j++)
{
if(s[j]==')')
{
if((st.top()).first=='a')
continue;
else
{
tim[(st.top()).second]=j+1;
st.pop();
}
}
else
{
st.push({s[j],j+1});
tim[j+1]=j+1;
}

}
while((st.top()).first!='a')
st.pop();
long long ind=0,index=0;
for(long long j=n;j>0;j--)
{
if(tim[j]!=0 && tim[j]!=j)
{
ind=tim[j];
index=j;
break;
}

}
for(long j=index-1;j>0;j--)
{
if(tim[j]==0)
{
tim[j]=ind;
}
else
{
if(tim[j]!=j)
ind=tim[j];
}
}

for(long long j=0;j<q;j++)
{
long long tm;
cin>>tm;
if(tim[tm]==tm)
cout<<-1<<endl;
else
{
if(tim[tm]!=0)
cout<<tim[tm]<<endl;
else
cout<<-1<<endl;

}
}
}
return 0;
}
``````

I have used a very simple logic. For each opening bracket, I store the corresponding closing bracket position. Also, I maintain an array to keep a track of all the opening bracket positions.
Now, suppose we have a query, we have 2 cases:
Case 1:The given index itself has an open bracket: This query can be answered in O(1) using the vector we have created.
Case 2: The given index has a closing bracket: We first find the nearest opening bracket and then use the answer for that.

Here is the link to my submission:
https://www.codechef.com/viewsolution/35686254

my logic gives WA. Can you please give me a testcase where it fails.