Number of balanced parentheses substrings

04 Jun, 2022
Given a balanced parentheses string which consists of ‘(‘ and ‘)‘. The task is to find the number of balanced parentheses substrings in the given string  
Examples :  
Input : str = “()()()” Output : 6 (), (), (), ()(), ()(), ()()()Input : str = “(())()” Output : 4 (), (()), (), (())() 
 
Approach : 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 : 
C++
Java
Python3
C#
Javascript
// CPP program to find number of// balanced parentheses sub strings#include <bits/stdc++.h>using namespace std; // Function to find number of// balanced parentheses sub stringsint Balanced_Substring(string str, int n){    // To store required answer    int ans = 0;     // Vector to stores the number of    // balanced brackets at each depth.    vector<int> arr(n / 2 + 1, 0);     // d stores checks the depth of our sequence    // For example level of () is 1    // and that of (()) is 2.    int d = 0;    for (int i = 0; i < n; i++) {        // If open bracket        // increase depth        if (str[i] == '(')            d++;         // If closing bracket        else {            if (d == 1) {                for (int j = 2; j <= n / 2 + 1 && arr[j] != 0; j++)                    arr[j] = 0;            }            ++ans;            ans += arr[d];            arr[d]++;            d--;        }    }     // Return the required answer    return ans;} // Driver codeint main(){    string str = "()()()";     int n = str.size();     // Function call    cout << Balanced_Substring(str, n);     return 0;}
// Java program to find number of// balanced parentheses sub stringsclass GFG {     // Function to find number of    // balanced parentheses sub strings    public static int Balanced_Substring(String str,                                         int n)    {         // To store required answer        int ans = 0;         // Vector to stores the number of        // balanced brackets at each depth.        int[] arr = new int[n / 2 + 1];         // d stores checks the depth of our sequence        // For example level of () is 1        // and that of (()) is 2.        int d = 0;        for (int i = 0; i < n; i++) {             // If open bracket            // increase depth            if (str.charAt(i) == '(')                d++;             // If closing bracket            else {                if (d == 1) {                    for (int j = 2; j <= n / 2 + 1 && arr[j] != 0; j++)                        arr[j] = 0;                }                ++ans;                ans += arr[d];                arr[d]++;                d--;            }        }         // Return the required answer        return ans;    }     // Driver code    public static void main(String[] args)    {        String str = "()()()";        int n = str.length();         // Function call        System.out.println(Balanced_Substring(str, n));    }} // This code is contributed by// sanjeev2552
# Python3 program to find number of# balanced parentheses sub strings # Function to find number of# balanced parentheses sub stringsdef Balanced_Substring(s, n):     # To store required answer    ans = 0;     # Vector to stores the number of    # balanced brackets at each depth.    arr = [0] * (int(n / 2) + 1);     # d stores checks the depth of our sequence    # For example level of () is 1    # and that of (()) is 2.    d = 0;    for i in range(n):         # If open bracket        # increase depth        if (s[i] == '('):            d += 1;         # If closing bracket        else:            if (d == 1):                j = 2                while (j <= n//2 + 1 and arr[j] != 0):                    arr[j] = 0            ans += 1;            ans += arr[d];            arr[d] += 1;            d -= 1;     # Return the required answer    return ans; # Driver codes = "()()()";n = len(s); # Function callprint(Balanced_Substring(s, n)); # This code contributed by Rajput-Ji
// C# program to find number of// balanced parentheses sub stringsusing System; class GFG {     // Function to find number of    // balanced parentheses sub strings    public static int Balanced_Substring(String str,                                         int n)    {         // To store required answer        int ans = 0;         // Vector to stores the number of        // balanced brackets at each depth.        int[] arr = new int[n / 2 + 1];         // d stores checks the depth of our sequence        // For example level of () is 1        // and that of (()) is 2.        int d = 0;        for (int i = 0; i < n; i++) {             // If open bracket            // increase depth            if (str[i] == '(')                d++;             // If closing bracket            else {                if (d == 1) {                    for (int j = 2; j <= n / 2 + 1 && arr[j] != 0; j++)                        arr[j] = 0;                }                ++ans;                ans += arr[d];                arr[d]++;                d--;            }        }         // Return the required answer        return ans;    }     // Driver code    public static void Main(String[] args)    {        String str = "()()()";        int n = str.Length;         // Function call        Console.WriteLine(Balanced_Substring(str, n));    }} // This code is contributed by Princi Singh
<script> // Javascript program to find number of// balanced parentheses sub strings // Function to find number of// balanced parentheses sub stringsfunction Balanced_Substring(str, n){    // To store required answer    let ans = 0;     // Vector to stores the number of    // balanced brackets at each depth.    let arr = new Array(n / 2 + 1).fill(0);     // d stores checks the depth of our sequence    // For example level of () is 1    // and that of (()) is 2.    let d = 0;    for (let i = 0; i < n; i++) {        // If open bracket        // increase depth        if (str[i] == '(')            d++;         // If closing bracket        else {            if (d == 1) {                for (let j = 2; j <= parseInt(n / 2) +                1 && arr[j] != 0; j++)                    arr[j] = 0;            }            ++ans;            ans += arr[d];            arr[d]++;            d--;        }    }     // Return the required answer    return ans;} // Driver code    let str = "()()()";     let n = str.length;     // Function call    document.write(Balanced_Substring(str, n)); </script>
6
 
Time complexity : O(N)
Auxiliary Space: O(N) 
sanjeev2552
princi singh
Rajput-Ji
gjaiswal108
subham348
arorakashish0911
saurabh1990aror
subhammahato348
Constructive Algorithms
substring
Greedy
Mathematical
Strings
Strings
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.