Loading...
Loading...
You are given a string s made only of the characters ( and ), and a list queries. Each element in queries contains [l, r] meaning the substring of s from position l to position r, inclusive. Positions are 1-based: the first character of s is at position 1.
A string is balanced if it has as many ( as ) and no prefix of it has more ) than (. For example, (())() is balanced, while )( and (() are not. The empty string is balanced.
A subsequence is what remains after deleting any number of characters (possibly none) without changing the order of the rest.
Return an array with one entry per query, in the same order as queries. The entry for [l, r] is the length of the longest balanced subsequence of the substring s[l..r]. If no ( in that substring comes before a ), the entry is 0.
Input: s = "(())(()(())"
queries = [[1, 1],
[1, 5],
[3, 6]]
Output: [0, 4, 0]
Explanation: Positions 1 to 1 hold "(", which has nothing to pair with, so the answer is 0. Positions 1 to 5 hold "(())(": the first four characters "(())" are balanced and the last "(" is left over, so the answer is 4. Positions 3 to 6 hold "))((": both "(" come after both ")", so no pair can form and the answer is 0.
Input: s = "())(())(())("
queries = [[1, 1],
[2, 3],
[1, 2],
[1, 12],
[8, 12],
[5, 11],
[2, 10]]
Output: [0, 0, 2, 10, 4, 6, 6]
Explanation: Positions 1 to 12 are the whole string. Deleting the ")" at position 3 and the "(" at position 12 leaves "()(())(())", which is balanced and has length 10. Positions 2 to 3 hold "))", so the answer is 0. Positions 5 to 11 hold "())(())": deleting the ")" at position 7 leaves "()(())", so the answer is 6.
s.length ≤2⋅105s consists only of the characters ( and )queries.length ≤105s.length for each [l, r] in queries