Given a balanced parenthesis string which consists of ‘(‘ and ‘)‘. The task is to find the number of balanced parenthesis substrings in the given string
Input : str = “()()()”
Output : 6
(), (), (), ()(), ()(), ()()()
Input : str = “(())()”
Output : 4
(), (()), (), (())()
Let us assume that whenever we encounter with opening bracket the depth increases by one and with a closing bracket the depth decreases by one. Whenever we encounter the closing bracket increase our required answer by one and then increment our required answer by the already formed balanced substrings at this depth.
Below is the implementation of the above approach :
Time complexity : O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
- Reverse substrings between each pair of parenthesis
- Find maximum depth of nested parenthesis in a string
- Identify and mark unmatched parenthesis in an expression
- Sum of all the numbers in the Nth parenthesis
- Count all indices of cyclic regular parenthesis
- Calculate weight of parenthesis based on the given conditions
- Number of substrings with length divisible by the number of 1's in it
- Minimum number of bracket reversals needed to make an expression balanced
- Number of balanced bracket subsequence of length 2 and 4
- Number of ways to partition a string into two balanced subsequences
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum number of additons to make the string balanced
- Balanced Ternary Number System
- Check if the number is balanced
- Check if N is a Balanced Prime number or not
- Given a binary string, count number of substrings that start and end with 1.
- Count number of substrings with exactly k distinct characters
- Count Substrings with equal number of 0s, 1s and 2s
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.