Number of closing brackets needed to complete a regular bracket sequence | Java program to find number of closing brackets needed and complete a regular bracket sequence ; Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then answer is impossible ; If possible , print ' s ' and required closing brackets . ; Driver code
class GFG { static void completeSequence ( String s ) { int n = s . length ( ) ; int open = 0 , close = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ' ( ' ) open ++ ; else close ++ ; if ( close > open ) { System . out . print ( " IMPOSSIBLE " ) ; return ; } } System . out . print ( s ) ; for ( int i = 0 ; i < open - close ; i ++ ) System . out . print ( " ) " ) ; } public static void main ( String [ ] args ) { String s = " ( ( ) ( ( ) ( " ; completeSequence ( s ) ; } }