Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2 | Java program to toggle K - th bit of a number N ; Function that returns true if the string can be balanced ; Count to check the difference between the frequencies of ' ( ' and ' ) ' and count_1 is to find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; Traverse the given string ; Increase the count ; Decrease the count ; Find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; If the minimum difference is greater than or equal to - 1 and the overall difference is zero ; Driver code
class GFG { static boolean canBeBalanced ( String s , int n ) { int count = 0 , count_1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ' ( ' ) count ++ ; else count -- ; count_1 = Math . min ( count_1 , count ) ; } if ( count_1 >= - 1 && count == 0 ) return true ; return false ; } public static void main ( String [ ] args ) { String s = " ( ) ) ( ) ( " ; int n = s . length ( ) ; if ( canBeBalanced ( s , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }