Count pairs of parentheses sequences such that parentheses are balanced - GeeksforGeeks

31 May, 2021
Given N bracket sequences, the task is to find the number of pairs of bracket sequences by joining which can be obtained a balanced bracket sequence as a whole. A bracket parentheses sequence can only be a part of a single pair. 
Examples: 
Input: { ")())", ")", "((", "((", "(", ")", ")"}
Output:  2 
Bracket sequence {1, 3} and {5, 6} 

Input: {"()", "(())", "(())", "()"}
Output: 2 
Since all brackets are balanced, hence we can form 2 pairs with 4. 
Approach: The following steps can be followed to solve the above problem: 
Count required opening and closing brackets, of individuals.
If required closing brackets > 0 and opening brackets is 0, then hash the bracket’s required closing number.
Similarly, if required opening brackets > 0 and closing brackets is 0, then hash the bracket’s required opening number.
Count the balanced bracket sequences.
Add (number of balanced bracket sequences/2) to the number of pairs.
For every number of sequences which requires same number of opening brackets, min(hash[open], hash[close]) will be added to the number of pairs
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to count the number of pairs// of balanced parentheses#include <bits/stdc++.h>using namespace std; // Function to count the number of pairsint countPairs(string bracks[], int num){     // Hashing function to count the    // opening and closing brackets    unordered_map<int, int> open, close;     int cnt = 0;     // Traverse for all bracket sequences    for (int i = 0; i < num; i++) {         // Get the string        string s = bracks[i];         int l = s.length();         // Counts the opening and closing required        int op = 0, cl = 0;         // Traverse in the string        for (int j = 0; j < l; j++) {             // If it is a opening bracket            if (s[j] == '(')                op++;            else // Closing bracket            {                 // If openings are there, then close it                if (op)                    op--;                else // Else increase count of closing                    cl++;            }        }         // If requirements of openings        // are there and no closing        if (op && !cl)            open[op]++;         // If requirements of closing        // are there and no opening        if (cl && !op)            close[cl]++;         // Perfect        if (!op && !cl)            cnt++;    }     // Divide by two since two    // perfect makes one pair    cnt = cnt / 2;     // Traverse in the open and find    // corresponding minimum    for (auto it : open)        cnt += min(it.second, close[it.first]);     return cnt;} // Driver Codeint main(){    string bracks[] = { ")())", ")", "((", "((", "(", ")", ")" };    int num = sizeof(bracks) / sizeof(bracks[0]);     cout << countPairs(bracks, num);}
// Java program to count the number of pairs// of balanced parenthesesimport java.util.HashMap; class GFG{ // Function to count the number of pairsstatic int countPairs(String[] bracks, int num){     // Hashing function to count the    // opening and closing brackets    HashMap<Integer, Integer> open = new HashMap<>();    HashMap<Integer, Integer> close = new HashMap<>();     int cnt = 0;     // Traverse for all bracket sequences    for (int i = 0; i < num; i++)    {         // Get the string        String s = bracks[i];        int l = s.length();         // Counts the opening and closing required        int op = 0, cl = 0;         // Traverse in the string        for (int j = 0; j < l; j++)        {             // If it is a opening bracket            if (s.charAt(j) == '(')                op++;             // Closing bracket            else            {                 // If openings are there, then close it                if (op != 0)                    op--;                 // Else increase count of closing                else                    cl++;            }        }         // If requirements of openings        // are there and no closing        if (op != 0 && cl == 0)            open.put(op, open.get(op) == null ?                     1 : open.get(op) + 1);         // If requirements of closing        // are there and no opening        if (cl != 0 && op == 0)            close.put(cl, close.get(cl) == null ?                      1 : close.get(cl) + 1);         // Perfect        if (op == 0 && cl == 0)            cnt++;    }     // Divide by two since two    // perfect makes one pair    cnt /= 2;     // Traverse in the open and find    // corresponding minimum    for (HashMap.Entry<Integer,                       Integer> it : open.entrySet())        cnt += Math.min(it.getValue(),              close.get(it.getKey()));     return cnt;} // Driver Codepublic static void main(String[] args){    String[] bracks = { ")())", ")", "((",                        "((", "(", ")", ")" };    int num = bracks.length;     System.out.println(countPairs(bracks, num));}} // This code is contributed by// sanjeev2552
# Python3 program to count the number of pairs# of balanced parenthesesimport math as mt # Function to count the number of pairsdef countPairs(bracks, num):     # Hashing function to count the    # opening and closing brackets    openn=dict()    close=dict()     cnt = 0     # Traverse for all bracket sequences    for i in range(num):         # Get the string        s = bracks[i]         l = len(s)         # Counts the opening and closing required        op,cl = 0,0         # Traverse in the string        for j in range(l):            # If it is a opening bracket            if (s[j] == '('):                op+=1            else: # Closing bracket                              # If openings are there, then close it                if (op):                    op-=1                else: # Else increase count of closing                    cl+=1                               # If requirements of openings        # are there and no closing        if (op and cl==0):            if op in openn.keys():                openn[op]+=1            else:                openn[op]=1                          # If requirements of closing        # are there and no opening        if (cl and op==0):            if cl in openn.keys():                close[cl]+=1            else:                close[cl]=1                      # Perfect        if (op==0 and cl==0):            cnt+=1          # Divide by two since two    # perfect makes one pair    cnt = cnt //2     # Traverse in the open and find    # corresponding minimum    for it in openn:        cnt += min(openn[it], close[it])     return cnt  # Driver Codebracks= [")())", ")", "((", "((", "(", ")", ")" ]num = len(bracks) print(countPairs(bracks, num)) #This code is contributed by Mohit kumar 29
// C# program to count the number of pairs// of balanced parenthesesusing System;using System.Collections.Generic;  class GFG{  // Function to count the number of pairsstatic int countPairs(string[] bracks, int num){       // Hashing function to count the    // opening and closing brackets    Dictionary<int,               int> open = new Dictionary<int,                                          int>();    Dictionary<int,               int> close = new Dictionary<int,                                           int>();      int cnt = 0;      // Traverse for all bracket sequences    for(int i = 0; i < num; i++)    {          // Get the string        string s = bracks[i];        int l = s.Length;          // Counts the opening and closing required        int op = 0, cl = 0;          // Traverse in the string        for(int j = 0; j < l; j++)        {              // If it is a opening bracket            if (s[j] == '(')                op++;              // Closing bracket            else            {                  // If openings are there, then close it                if (op != 0)                    op--;                  // Else increase count of closing                else                    cl++;            }        }          // If requirements of openings        // are there and no closing        if (op != 0 && cl == 0)        {            if (open.ContainsKey(op))            {                open[op]++;            }            else            {                open[op] = 1;            }        }          // If requirements of closing        // are there and no opening        if (cl != 0 && op == 0)        {            if (close.ContainsKey(cl))            {                close[cl]++;            }            else            {                close[cl] = 1;            }        }          // Perfect        if (op == 0 && cl == 0)            cnt++;    }      // Divide by two since two    // perfect makes one pair    cnt /= 2;      // Traverse in the open and find    // corresponding minimum    foreach(KeyValuePair<int, int> it in open)    {        cnt += Math.Min(it.Value, close[it.Value]);    }    return cnt;}  // Driver Codepublic static void Main(string[] args){    string[] bracks = { ")())", ")", "((",                        "((", "(", ")", ")" };       int num = bracks.Length;      Console.Write(countPairs(bracks, num));}} // This code is contributed by rutvik_56
<script>// Javascript program to count the number of pairs// of balanced parentheses // Function to count the number of pairsfunction countPairs( bracks,num){     // Hashing function to count the    // opening and closing brackets    let open = new Map();    let close = new Map();    let cnt = 0;      // Traverse for all bracket sequences    for (let i = 0; i < num; i++)    {          // Get the string        let s = bracks[i];        let l = s.length;          // Counts the opening and closing required        let op = 0, cl = 0;          // Traverse in the string        for (let j = 0; j < l; j++)        {              // If it is a opening bracket            if (s[j] == '(')                op++;              // Closing bracket            else            {                  // If openings are there, then close it                if (op != 0)                    op--;                  // Else increase count of closing                else                    cl++;            }        }          // If requirements of openings        // are there and no closing        if (op != 0 && cl == 0)            open.set(op, open.get(op) == null ?                     1 : open.get(op) + 1);          // If requirements of closing        // are there and no opening        if (cl != 0 && op == 0)            close.set(cl, close.get(cl) == null ?                      1 : close.get(cl) + 1);          // Perfect        if (op == 0 && cl == 0)            cnt++;    }      // Divide by two since two    // perfect makes one pair    cnt /= 2;      // Traverse in the open and find    // corresponding minimum    for (let [key, value] of open.entries())        cnt += Math.min(value,              close.get(value));      return cnt;} // Driver Codelet bracks=[")())", ")", "((",                        "((", "(", ")", ")"];                         let num = bracks.length;document.write(countPairs(bracks, num)); // This code is contributed by patel2127</script>
2
 
mohit kumar 29
Akanksha_Rai
sanjeev2552
AJITNAIN
rutvik_56
patel2127
cpp-unordered_map
Hash
Parentheses-Problems
Competitive Programming
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bits manipulation (Important tactics)
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
How to begin with Competitive Programming?
Use of FLAG in programming
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string