Given a string of brackets, task is to find the number of pairs of brackets involved in a balanced sequence in a given range.
Input : ((())(() Range : 1 5 Range : 3 8 Output : 2 2 Explanation : In range 1 to 5 ((()), there are the two pairs. In range 3 to 8 ()) ((), there are the two pairs. Input : )()())) Range : 1 2 Range : 4 7 Output : 0 1 Explanation : In range 1 to 2 )( there is no any pair. In range 4 to 7 ())), there is the only pair
Prerequisite : Segment Trees
Here, in segment tree, for each node, keep some simple elements, like integers or sets or vectors or etc.
For each node keep three integers :
1. t = Answer for the interval.
2. o = The number of opening brackets ‘(‘ remaining after deleting the brackets those who belong to the correct bracket sequence in this interval whit length t.
3. c = The number of closing brackets ‘)’ remaining after deleting the brackets those who belong to the correct bracket sequence in this interval whit length t.
Now, having these variables, queries can be answered easily using segment tree.
Below is the implementation of above approach :
- Count pairs of parentheses sequences such that parentheses are balanced
- Print all combinations of balanced parentheses
- Length of longest balanced parentheses prefix
- Check for balanced parentheses in an expression | O(1) space
- Check for balanced parentheses in Python
- Check for balanced parentheses in an expression
- Number of ways to insert two pairs of parentheses into a string of N characters
- Remove Invalid Parentheses
- Find the number of valid parentheses expressions of given length
- Minimum number of Parentheses to be added to make it valid
- Balance the parentheses for the given number N
- Score of Parentheses using Tree
- How to determine if a binary tree is height-balanced?
- Sorted Array to Balanced BST
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Convert a normal BST to Balanced BST
- Count Balanced Binary Trees of Height h
- Practice questions on Height balanced/AVL Tree
- Split a BST into two balanced BSTs based on a value K
- Check if concatenation of two strings is balanced or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : andrew1234