Count pairs of parentheses sequences such that parentheses are balanced | Function to count the number of pairs ; Hashing function to count the opening and closing brackets ; Traverse for all bracket sequences ; Get the string ; Counts the opening and closing required ; Traverse in the string ; If it is a opening bracket ; Closing bracket ; If openings are there , then close it ; Else increase count of closing ; If requirements of openings are there and no closing ; If requirements of closing are there and no opening ; Perfect ; Divide by two since two perfect makes one pair ; Traverse in the open and find corresponding minimum ; Driver Code
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 ) ) ;