Number of balanced parenthesis substrings

Given a balanced parenthesis string which consists of ‘(‘ and ‘)‘. The task is to find the number of balanced parenthesis 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find number of
// balanced parenthesis sub strings
#include <bits/stdc++.h>
using namespace std;
  
// Function to find number of
// balanced parenthesis sub strings
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.
    vector<int> arr(n / 2 + 1, 0);
  
    // d strores 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 {
            ++ans;
            ans += arr[d];
            arr[d]++;
            d--;
        }
    }
  
    // Return the required answer
    return ans;
}
  
// Driver code
int main()
{
    string str = "()()()";
  
    int n = str.size();
  
    // Function call
    cout << Balanced_Substring(str, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find number of 
// balanced parenthesis sub strings 
class GFG
{
  
    // Function to find number of
    // balanced parenthesis 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 strores 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 
            {
                ++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

chevron_right


Python3

# Python3 program to find number of
# balanced parenthesis sub strings

# Function to find number of
# balanced parenthesis sub strings
def 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 strores 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:
ans += 1;
ans += arr[d];
arr[d] += 1;
d -= 1;

# Return the required answer
return ans;

# Driver code
s = “()()()”;
n = len(s);

# Function call
print(Balanced_Substring(s, n));

# This code contributed by Rajput-Ji

C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find number of 
// balanced parenthesis sub strings
using System;
      
class GFG
{
  
    // Function to find number of
    // balanced parenthesis 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 strores 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
            {
                ++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

chevron_right


Output:

6

Time complexity : O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.