![]() |
VOOZH | about |
Given a string s of length n, consisting of opening and closing brackets and an array queries[] consisting of q queries of type [start, end], where start defines the starting point and end defines the ending point. For each query, the task is to find the maximum length of the valid bracket subsequence from index start to end.
Note: A correct bracket sequence has matched bracket pairs or contains another nested correct bracket sequence.
Examples:
Input: s = "())(())(())(", start = 0, end = 11
Output: 10
Explanation: Longest Correct Bracket Subsequence is ()(())(())Input : s = "())(())(())(", start = 1, end = 2
Output : 0
Explanation: There is no correct bracket subsequence.
Note: An approach using stack and pre-computed lengths has been discussed in article Range Query Set 2 that works in O(1) for each query.
Approach:
Segment Trees can be used to solve this problem efficiently At each node of the segment tree, we store the following:
- Number of correctly matched pairs of brackets
- Number of unused open brackets
- Number of unused closed brackets
For each interval [L, R], we can match X number of unused open brackets '(' in interval [L, MID] with unused closed brackets ')' in interval [MID + 1, R] where X = minimum(number of unused '(' in [L, MID], number of unused ')' in [MID + 1, R]) Hence, X is also the number of correctly matched pairs built by combination. So, for interval [L, R]
- Total number of correctly matched pairs becomes the sum of correctly matched pairs in left child and correctly matched pairs in right child and number of combinations of unused '(' and unused ')' from left and right child respectively a[L, R] = a[L, MID] + a[MID + 1, R] + X
- Total number of unused open brackets becomes the sum of unused open brackets in left child and unused open brackets in right child minus X (minus - because we used X unused '(' from left child to match with unused ') from right child) a[L, R] = b[L, MID] + b[MID + 1, R] - X
- Similarly, for unused closed brackets, following relation holds a[L, R] = c[L, MID] + c[MID + 1, R] - X
where a, b and c are the representations described above for each node to be stored in
Below is the implementation of the above approach:
6 0 2 2 0
Time complexity: O(n * log n), where n is the size of the string
Auxiliary Space: O(n)