Given an array arr[] of N strings such that each string consists of characters ‘(‘ and ‘)’, the task is to find the maximum number of pairs of strings such that the concatenation of the two strings is a Regular Bracket Sequence.
A Regular Bracket Sequence is a string consisting of brackets ‘(‘ and ‘)’ such that every prefix from the beginning of the string must have count of ‘(‘ greater than or equal to count of ‘)’ and count of ‘(‘ and ‘)’ are equal in the whole string. For Examples: “(())”, “()((()))”, …, etc
Examples:
Input: arr[] = {“) ( ) )”, “)”, “( (“, “( (“, “(“, “)”, “)”}
Output: 2
Explanation:
Following are the pair of strings:
- (2, 1): The string at indices are “((“ and “)())”. Now, the concatenation of these string is “(()())” which is a regular bracket sequence.
- (4, 5): The string at indices are “(“ and “)”. Now, the concatenation of these string is “()” which is a regular bracket sequence.
Therefore, the total count of pairs of regular bracket sequence is 2.
Input: arr[] = {“( ( ) )”, “( )”}
Output: 1
Naive Approach: The simplest approach to solve the given problem is to generate all possible pairs of strings from the given array and count those pairs whose concatenation results in the Regular Bracket Sequence. After checking for all possible pairs, print the total count obtained.
Time Complexity: O(L*N2), where L is the maximum length of the string.
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by describing each string by a pair (A, B), where A and B are the smallest values such that after adding A opening parentheses “(“ to the left of the string and B closing parentheses “)” to the right of the string it becomes a regular bracket sequence. To concatenate two-bracket sequences (say, ith and jth) in order to produce a correct bracket sequence, the excess of the opening parentheses in the i-th sequence must equal the excess of the closing parentheses in the jth sequence; that is, bi = aj. Follow the steps below to solve the problem:
- Initialize two arrays, say open[] and close[] to 0. Also, initialize an integer variable ans to 0 that stores the resultant count of pairs.
- Traverse the given array and perform the following steps:
- Find the number of opening and closing parentheses needed to be added to the left and right of arr[i] respectively to make arr[i] a regular bracket sequence using the approach discussed in this article. Let the values be a and b respectively.
- If a!=0 and b!=0 then arr[i] will require parenthesis on both of its sides so it is not possible to concatenate it with any other string.
- If a==0 and b==0 then this particular string is already a regular bracket sequence and can be paired with other strings which are regular bracket sequences.
- Otherwise, if a is equal to 0, then increment close[b] by 1 else increment open[a] by 1.
- Add the value of floor of (close[0]/2) to the value of ans.
- Traverse the array open[] and add the value of a minimum of open[i] and close[i] to the variable ans.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:-
C++
#include <bits/stdc++.h>
using namespace std;
void countPairs( int N, vector<string>arr)
{
vector< int >open(100,0);
vector< int >close(100,0);
int ans = 0;
for ( int i = 0; i < N; i++){
vector< char >c;
for ( auto j : arr[i]){
c.push_back(j);
}
int d = 0;
int minm = 0;
for ( int j = 0; j < c.size(); j++){
if (c[j] == '(' )
d += 1;
else {
d -= 1;
if (d < minm)
minm = d;
}
}
if (d >= 0){
if (minm == 0)
close[d]++;
}
else if (d < 0){
if (minm == d)
open[-d]++;
}
}
ans += floor (close[0]/2);
for ( int i = 1; i < 100; i++)
ans +=min(open[i], close[i]);
cout<<ans<<endl;
}
int main(){
int N = 7;
vector<string>list;
list.push_back( ")())" );
list.push_back( ")" );
list.push_back( "((" );
list.push_back( "((" );
list.push_back( "(" );
list.push_back( ")" );
list.push_back( ")" );
countPairs(N, list);
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void countPairs(
int N, ArrayList<String> arr)
{
int open[] = new int [ 100 ];
int close[] = new int [ 100 ];
int ans = 0 ;
for ( int i = 0 ; i < N; i++) {
char c[] = arr.get(i).toCharArray();
int d = 0 ;
int min = 0 ;
for ( int j = 0 ; j < c.length; j++) {
if (c[j] == '(' ) {
d++;
}
else {
d--;
if (d < min)
min = d;
}
}
if (d >= 0 ) {
if (min == 0 )
close[d]++;
}
else if (d < 0 ) {
if (min == d)
open[-d]++;
}
}
ans += close[ 0 ] / 2 ;
for ( int i = 1 ; i < 100 ; i++) {
ans += Math.min(
open[i], close[i]);
}
System.out.println(ans);
}
public static void main(String[] args)
{
int N = 7 ;
ArrayList<String> list = new ArrayList<String>();
list.add( ")())" );
list.add( ")" );
list.add( "((" );
list.add( "((" );
list.add( "(" );
list.add( ")" );
list.add( ")" );
countPairs(N, list);
}
}
|
Python3
def countPairs(N, arr):
open = [ 0 ] * 100
close = [ 0 ] * 100
ans = 0
for i in range (N):
c = [i for i in arr[i]]
d = 0
minm = 0
for j in range ( len (c)):
if (c[j] = = '(' ):
d + = 1
else :
d - = 1
if (d < minm):
minm = d
if (d > = 0 ):
if (minm = = 0 ):
close[d] + = 1
elif (d < 0 ):
if (minm = = d):
open [ - d] + = 1
ans + = close[ 0 ] / / 2
for i in range ( 1 , 100 ):
ans + = min ( open [i], close[i])
print (ans)
if __name__ = = '__main__' :
N = 7
list = []
list .append( ")())" )
list .append( ")" )
list .append( "((" )
list .append( "((" )
list .append( "(" )
list .append( ")" )
list .append( ")" )
countPairs(N, list )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void countPairs( int N, List< string > arr)
{
int [] open = new int [100];
int [] close = new int [100];
int ans = 0;
for ( int i = 0; i < N; i++)
{
char [] c = arr[i].ToCharArray();
int d = 0;
int min = 0;
for ( int j = 0; j < c.Length; j++)
{
if (c[j] == '(' )
{
d++;
}
else
{
d--;
if (d < min)
min = d;
}
}
if (d >= 0)
{
if (min == 0)
close[d]++;
}
else if (d < 0)
{
if (min == d)
open[-d]++;
}
}
ans += close[0] / 2;
for ( int i = 1; i < 100; i++)
{
ans += Math.Min(open[i], close[i]);
}
Console.WriteLine(ans);
}
public static void Main( string [] args)
{
int N = 7;
List< string > list = new List< string >();
list.Add( ")())" );
list.Add( ")" );
list.Add( "((" );
list.Add( "((" );
list.Add( "(" );
list.Add( ")" );
list.Add( ")" );
countPairs(N, list);
}
}
|
Javascript
<script>
function countPairs(N, arr)
{
let open = new Array(100).fill(0)
let close = new Array(100).fill(0)
let ans = 0
for (let i = 0; i < N; i++){
let c = [];
for (let j of arr[i]){
c.push(j);
}
let d = 0
let minm = 0
for (let j = 0; j < c.length; j++){
if (c[j] == '(' )
d += 1
else {
d -= 1
if (d < minm)
minm = d
}
}
if (d >= 0){
if (minm == 0)
close[d]++
}
else if (d < 0){
if (minm == d)
open[-d]++
}
}
ans += Math.floor(close[0]/2)
for (let i = 1; i < 100; i++)
ans +=Math.min(open[i], close[i])
document.write(ans)
}
let N = 7
let list = []
list.push( ")())" )
list.push( ")" )
list.push( "((" )
list.push( "((" )
list.push( "(" )
list.push( ")" )
list.push( ")" )
countPairs(N, list)
</script>
|
Time Complexity: O(L*N), where N is the maximum length of the string.
Auxiliary Space: O(L)