At first, replace the given bracket sequence by an integer array .
In this array,
a[i] = count of opening bracket till index i - count of closing bracket till index i
Now in each query, we need to find the maximum possible index x, in the range from l to r where and no element from to is less than . To do this, first check if there is any element from to that is less than . Find the first occurrence of such an element. This can be done using segment tree in time complexity. If such an element exists, replace with the index of that element. Then find the maximum index between and where . This can be found by using binary search. The output will be .
Time complexity .
This problem can also be solved by using sparse table. Time complexity is same .