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.
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
- Reverse substrings between each pair of parenthesis
- Check if the number is balanced
- Check if N is a Balanced Prime number or not
- Number of substrings with length divisible by the number of 1's in it
- Number of balanced bracket subsequence of length 2 and 4
- Number of ways to partition a string into two balanced subsequences
- Minimum number of additons to make the string balanced
- Number of substrings of a string
- Number of substrings divisible by 8 but not by 3
- Number of substrings with count of each character as k
- Number of substrings that start with "geeks" and end with "for"
- Sum of all substrings of a string representing a number | Set 1
- Number of even substrings in a string of digits
- Number of substrings of one string present in other
- Count Substrings with equal number of 0s, 1s and 2s
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum number of bracket reversals needed to make an expression balanced
- Count number of substrings with exactly k distinct characters
- Count number of substrings with numeric value greater than X
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.