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 are 0, then hash the bracket’s required closing number.
- Similarly, if required opening brackets > 0 and closing brackets are 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 that 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++
#include <bits/stdc++.h>
using namespace std;
int countPairs(string bracks[], int num)
{
unordered_map< int , int > open, close;
int cnt = 0;
for ( int i = 0; i < num; i++) {
string s = bracks[i];
int l = s.length();
int op = 0, cl = 0;
for ( int j = 0; j < l; j++) {
if (s[j] == '(' )
op++;
else
{
if (op)
op--;
else
cl++;
}
}
if (op && !cl)
open[op]++;
if (cl && !op)
close[cl]++;
if (!op && !cl)
cnt++;
}
cnt = cnt / 2;
for ( auto it : open)
cnt += min(it.second, close[it.first]);
return cnt;
}
int main()
{
string bracks[] = { ")())" , ")" , "((" , "((" , "(" , ")" , ")" };
int num = sizeof (bracks) / sizeof (bracks[0]);
cout << countPairs(bracks, num);
}
|
Java
import java.util.HashMap;
class GFG
{
static int countPairs(String[] bracks, int num)
{
HashMap<Integer, Integer> open = new HashMap<>();
HashMap<Integer, Integer> close = new HashMap<>();
int cnt = 0 ;
for ( int i = 0 ; i < num; i++)
{
String s = bracks[i];
int l = s.length();
int op = 0 , cl = 0 ;
for ( int j = 0 ; j < l; j++)
{
if (s.charAt(j) == '(' )
op++;
else
{
if (op != 0 )
op--;
else
cl++;
}
}
if (op != 0 && cl == 0 )
open.put(op, open.get(op) == null ?
1 : open.get(op) + 1 );
if (cl != 0 && op == 0 )
close.put(cl, close.get(cl) == null ?
1 : close.get(cl) + 1 );
if (op == 0 && cl == 0 )
cnt++;
}
cnt /= 2 ;
for (HashMap.Entry<Integer,
Integer> it : open.entrySet())
cnt += Math.min(it.getValue(),
close.get(it.getKey()));
return cnt;
}
public static void main(String[] args)
{
String[] bracks = { ")())" , ")" , "((" ,
"((" , "(" , ")" , ")" };
int num = bracks.length;
System.out.println(countPairs(bracks, num));
}
}
|
Python3
import math as mt
def countPairs(bracks, num):
openn = dict ()
close = dict ()
cnt = 0
for i in range (num):
s = bracks[i]
l = len (s)
op,cl = 0 , 0
for j in range (l):
if (s[j] = = '(' ):
op + = 1
else :
if (op):
op - = 1
else :
cl + = 1
if (op and cl = = 0 ):
if op in openn.keys():
openn[op] + = 1
else :
openn[op] = 1
if (cl and op = = 0 ):
if cl in openn.keys():
close[cl] + = 1
else :
close[cl] = 1
if (op = = 0 and cl = = 0 ):
cnt + = 1
cnt = cnt / / 2
for it in openn:
cnt + = min (openn[it], close[it])
return cnt
bracks = [ ")())" , ")" , "((" , "((" , "(" , ")" , ")" ]
num = len (bracks)
print (countPairs(bracks, num))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countPairs( string [] bracks, int num)
{
Dictionary< int ,
int > open = new Dictionary< int ,
int >();
Dictionary< int ,
int > close = new Dictionary< int ,
int >();
int cnt = 0;
for ( int i = 0; i < num; i++)
{
string s = bracks[i];
int l = s.Length;
int op = 0, cl = 0;
for ( int j = 0; j < l; j++)
{
if (s[j] == '(' )
op++;
else
{
if (op != 0)
op--;
else
cl++;
}
}
if (op != 0 && cl == 0)
{
if (open.ContainsKey(op))
{
open[op]++;
}
else
{
open[op] = 1;
}
}
if (cl != 0 && op == 0)
{
if (close.ContainsKey(cl))
{
close[cl]++;
}
else
{
close[cl] = 1;
}
}
if (op == 0 && cl == 0)
cnt++;
}
cnt /= 2;
foreach (KeyValuePair< int , int > it in open)
{
cnt += Math.Min(it.Value, close[it.Value]);
}
return cnt;
}
public static void Main( string [] args)
{
string [] bracks = { ")())" , ")" , "((" ,
"((" , "(" , ")" , ")" };
int num = bracks.Length;
Console.Write(countPairs(bracks, num));
}
}
|
Javascript
<script>
function countPairs( bracks,num)
{
let open = new Map();
let close = new Map();
let cnt = 0;
for (let i = 0; i < num; i++)
{
let s = bracks[i];
let l = s.length;
let op = 0, cl = 0;
for (let j = 0; j < l; j++)
{
if (s[j] == '(' )
op++;
else
{
if (op != 0)
op--;
else
cl++;
}
}
if (op != 0 && cl == 0)
open.set(op, open.get(op) == null ?
1 : open.get(op) + 1);
if (cl != 0 && op == 0)
close.set(cl, close.get(cl) == null ?
1 : close.get(cl) + 1);
if (op == 0 && cl == 0)
cnt++;
}
cnt /= 2;
for (let [key, value] of open.entries())
cnt += Math.min(value,
close.get(value));
return cnt;
}
let bracks=[ ")())" , ")" , "((" ,
"((" , "(" , ")" , ")" ];
let num = bracks.length;
document.write(countPairs(bracks, num));
</script>
|
Complexity Analysis:
- Time Complexity: O(N*M), as we are using nested loops to traverse N*M times.Where N is the number of strings in the bracks and M is the maximum length of the strings present in the bracks.
- Auxiliary Space: O(N), as we are using extra space for the map. Where N is the number of strings in the bracks.