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)
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
- Number of substrings divisible by 8 but not by 3
- Number of substrings of a string
- Number of balanced bracket subsequence of length 2 and 4
- Number of substrings of one string present in other
- Number of substrings with count of each character as k
- Number of substrings that start with "geeks" and end with "for"
- Count Substrings with equal number of 0s, 1s and 2s
- Number of even substrings in a string of digits
- Sum of all substrings of a string representing a number | Set 1
- Number of ways to partition a string into two balanced subsequences
- Minimum number of additons to make the string balanced
- Number of substrings divisible by 6 in a string of integers
- Count number of substrings with exactly k distinct characters
- Count number of distinct substrings of a given length
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.