At first, replace the given bracket sequence by an integer array aa.

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 a[x]=a[l1]a[x]=a[l-1] and no element from a[l]a[l] to a[x]a[x] is less than a[l1]a[l-1]. To do this, first check if there is any element from a[l]a[l] to a[r]a[r] that is less than a[l1]a[l-1]. Find the first occurrence of such an element. This can be done using segment tree in O(N×log(N))O(N \times log(N)) time complexity. If such an element exists, replace rr with the index of that element. Then find the maximum index yy between ll and rr where a[y]=a[l1]a[y]=a[l-1]. This can be found by using binary search. The output will be yl+1y-l+1.

Time complexity O(N×log(N))O(N × log(N)).

This problem can also be solved by using sparse table. Time complexity is same O(N×log(N))O(N × log(N)).

Contributors

Statistics

54% Solution Ratio
EgorKulikovEarliest, Jan '20
mumith_fahim99Fastest, 0.1s
AMDAD_MBSTULightest, 12 MB
Riaz_BSMRSTUShortest, 839B
Toph uses cookies. By continuing you agree to our Cookie Policy.