VOOZH about

URL: https://www.geeksforgeeks.org/dsa/range-queries-longest-correct-bracket-subsequence-set-2/

⇱ Range Queries for Longest Correct Bracket Subsequence Set | 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Range Queries for Longest Correct Bracket Subsequence Set | 2

Last Updated : 11 Jul, 2025

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

Note: An approach using Segment Tree has been discussed in article Range Query Set 1 that works in O(log n) for each query.

Approach:

The idea is to pre-compute the valid bracket subsequences for each index of string s. To do so, create two arrays open[] and close[], each of size n, where open[] marks the valid open bracket and close[] marks the valid closing bracket. Also, create a stack to store the indices of opening brackets. Start from the 0th index, if the character is '(' store the index in stack, else check if stack is not empty i.e. at least one opening bracket is yet unmatched, if so, remove the index from stack, and mark both open[] and close[] arrays. At last, transform these two arrays to store the prefix sum representing the number of valid brackets up to index i.
Now for each query [start, end], (close[end] - open[start - 1]) * 2 is the longest valid subsequence.

Below is the implementation of the above idea.


Output
6 0 2 2 0 

Time Complexity: O(n + q), O(1) for each query.
Auxiliary Space: O(n)

Comment